WeChat applet download, save, open file

The process of downloading the stream file directly


```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]
   })

Note:
1. The open file function needs to pass in the format of the file. At the beginning, the file format type is taken from the response, and the ios side reports an error. The correct operation is to take it from the onHeadersReceiver function.
2. When the file is empty, some mobile phones will also report an error, but I haven’t tested the specific mobile phones. There is no difference between ios and Android, so the file is empty, but a prompt message is displayed.

Guess you like

Origin blog.csdn.net/lb1135909273/article/details/103628209