情境:小程式調用 wx.downloadFile() API 下載檔案,PHP後端做處理並返迴文件流程;
流程:
1.小程式展示需要下載的檔案清單;
2.點擊下載後請求PHP介面,攜帶一個參數為想要下載的檔案名稱;
3.在PHP接收該參數,然後在檔案夾尋找是否有該檔案;
4.找到檔案後把該檔案返回給小程式端;
5.小程式端儲存後端返回的檔案,點擊開啟檔案,實現預覽
小程式端代碼:
wxml
<view>檔案清單</view><view wx:for='{{search_store}}' wx:key='{{index}}'> <view bindtap='dom' id='{{index}}'>檔案名稱:{{item.fileName}} 點擊下載</view></view>
js
dom: function (e) { var index = e.currentTarget.id; var data = this.data.search_store[index].fileName var that = this; wx.downloadFile({ url: 'https://dwb.lynncain.cn/H5/dom.php?str=' + data, //下載路徑攜帶 參數=檔案名稱 success: function (res) { console.log(res.tempFilePath) wx.saveFile({ //下載成功後儲存 tempFilePath: res.tempFilePath, success: function (res) { wx.showToast({ title: '下載成功!', }) wx.getSavedFileList({ //擷取下載的檔案清單儲存到data success: function (rrr) { console.log(rrr.fileList) that.setData({ fileList: rrr.fileList }) } }) } }) } }) },
php
<?php header("Access-Control-Allow-Origin: *"); //解決跨域 header('Access-Control-Allow-Methods:GET');// 響應類型 header('Access-Control-Allow-Headers:*'); // 回應標頭設定 $link=mysql_connect("localhost","root","root"); mysql_select_db("new_test", $link); //選擇資料庫 mysql_query("SET NAMES utf8");//解決中文亂碼問題error_reporting(0);$str = $_GET['str'];$file_path="upload/".$str;if (! file_exists ( $file_path )) { header('HTTP/1.1 404 NOT FOUND'); } else { //以唯讀和二進位模式開啟檔案 $file = fopen ( $file_path, "rb" ); //告訴瀏覽器這是一個檔案流格式的檔案 Header ( "Content-type: application/octet-stream" ); //請求範圍的度量單位 Header ( "Accept-Ranges: bytes" ); //Content-Length是指定包含於請求或響應中資料的位元組長度 Header ( "Accept-Length: " . filesize ( $file_path ) ); //用來告訴瀏覽器,檔案是可以當做附件被下載,下載後的檔案名稱為$file_name該變數的值。Header ( "Content-Disposition: attachment; filename=" . $str ); //讀取檔案內容並直接輸出到瀏覽器 echo fread ( $file, filesize ( $file_path ) ); fclose ( $file ); exit (); } ?>
本文介紹了小程式下載檔案,如何通過後端PHP處理,更多相關知識請關注php中文網。