1. 程式人生 > >微信小程式下載檔案,後端PHP處理流程

微信小程式下載檔案,後端PHP處理流程

 有問題可以掃碼加我微信,有償解決問題。承接小程式開發。

微信小程式開發交流qq群   173683895  、 526474645 ;

正文:


場景:微信小程式呼叫 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 ();    
		}    


?>