微信小程序下载、保存、打开文件

直接下载流文件过程


```javascript
wx.downloadFile({
     url: app.globalData.url + '/material/handleBlackFileDownload?id=' + id,
     success(res) {
       console.log(res)
       if (res.statusCode === 200) {
         filePath = res.tempFilePath
         wx.saveFile({
           tempFilePath: filePath,
           success(res) {
             const savedFilePath = res.savedFilePath
             that.setData({
               downLoading: false
             })
             wx.openDocument({
               filePath: savedFilePath,
               fileType: fileType,
               success: function (response) {
                 $Message({
                   content: '文件下载成功,打开中',
                   type: 'success'
                 })
               },
               fail: function (res) {
                 $Message({
                   content: '文件下载成功,打开失败,请手动打开',
                   type: 'error'
                 })
               }
             })
           },
           fail(err){
             $Message({
               content: '文件保存失败',
               type: 'error'
             })
           }
         })
       } else {
         $Message({
           content: '文件下载失败',
           type: 'error'
         })
       }  
     },
     fail(err) {
       that.setData({
         downLoading: false
       })
       console.log(err)
       $Message({
         content: '文件为空,下载失败',
         type: 'error'
       })
     }
   }).onHeadersReceived(header => {
     console.log(header)
     fileType = header.header["Content-Disposition"].split('.')[1]
   })

注意:
1.打开文件函数需要传入文件的格式,刚开始文件格式类型从response中取,ios端报错,正确操作是从onHeadersReceiver函数中取
2.文件为空时,部分手机也会报错,但是还没测试出具体是哪些手机,ios和安卓没有差别,所以文件为空,可是显示提示信息

猜你喜欢

转载自blog.csdn.net/lb1135909273/article/details/103628209
今日推荐