本文實例講述了微信小程序學習筆記之文件上傳、下載操作。分享給大家供大家參考,具體如下:
前面介紹了微信小程序登錄API與獲取用戶信息操作。這里再來介紹一下文件的上傳與下載操作。
【文件上傳】wx.uploadFile
(以上傳圖片為例)
后臺上傳接口Upload.php:(tp5)
<?phpnamespace app/home/controller;use think/Controller;class Upload extends First{ //上傳圖片API public function upImg() { $arr = array('state'=>0,'msg'=>'上傳失敗','filepath'=>''); $file = request()->file('file'); if($file){ $info = $file->move('upload/weixin/'); if ($info) { $arr['state'] = 1; $arr['msg'] = '上傳成功'; $arr['filepath'] = $info->getSaveName(); } } return json($arr); }}前臺頁面upload.wxml:
<image src='{{imgpath}}' style='width:600rpx; height:600rpx' /><view> <button bindtap="upImg">點擊選擇上傳圖</button></view>前臺upload.js:
Page({ data: { imgpath: '' }, upImg: function (e) { var that = this wx.chooseImage({ count: 1, // 默認最多一次上傳9張圖片 sizeType: ['original', 'compressed'], // 允許原圖和壓縮圖 sourceType: ['album', 'camera'], // 允許相冊和相機 success(res) { const tempFilePaths = res.tempFilePaths wx.showToast({ title: '正在上傳...', icon: 'loading', mask: true, duration: 500 }) wx.uploadFile({ url: 'https://www.msllws.top/Upload/upImg', //服務器上傳接口 filePath: tempFilePaths[0], //文件資源路徑 name: 'file', header: { 'Content-Type': 'Application/json' }, success(res) { console.log(res) if (res.statusCode == 200){ that.setData({ imgpath: tempFilePaths }) } } }) } }) }})演示效果:

(其實是有正在上傳...效果的,手機錄屏沒給錄上。。)

查看服務器里面多了一張圖片:

嗯哼~

【文件下載】wx.downloadFile
(以下載一張圖片為例)
在服務器目錄下放一張圖片1.jpg:


download.wxml:
<image src='{{imgpath}}' style='width:600rpx; height:600rpx' /><view> <button bindtap="download">點擊下載</button></view>download.js:
Page({ data: { imgpath: '' }, download: function (e) { var that = this wx.showToast({ title: '正在下載...', icon: 'loading', mask: true, duration: 500 }) wx.downloadFile({ url: 'https://www.msllws.top/upload/1.jpg', //下載地址 type: 'image', //下載的資源類型(imnage/audio/video) success: function (res) { console.log(res) if (res.statusCode == 200) { var filepath = res.tempFilePath that.setData({ imgpath: filepath }) } } }) }})演示效果:


希望本文所述對大家微信小程序開發有所幫助。
新聞熱點
疑難解答