微信小程式下載檔案,如何通過後端PHP處理

來源:互聯網
上載者:User
情境:小程式調用 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中文網。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.