微信小程序文件的下载,保存与打开

这里涉及到的API:wx.downloadFile,wx.saveFile,wx.openDocument

相应的官方文档

这里需要注意的地方是:wx.openDocument的fileType文件类型需要写正确,否则微信小程序返回的文件类型是.exe类型,ios就会出现文件类型损坏,打不开文件。

下面是相应的代码:

let fileUrl = BASE_URL + '/api/manage/loadRoster?projectId=' + projectId
//fileUrl 指下载文件api
    wx.showLoading({ 
    title: ''
})				
    wx.downloadFile({ 
      url: fileUrl,
      success: (res) => { 
        console.log(res)
    
        if (res.statusCode === 200) { 
          let filePath = res.tempFilePath
          wx.saveFile({ 
            tempFilePath: filePath,
            success: (res1) => { 
                const savedFilePath = res1.savedFilePath
    
                wx.hideLoading();
                this.toast('文件下载成功,打开中')
    
                wx.openDocument({ 
                    filePath: savedFilePath,
                    fileType: 'xlsx', //注意:文件为excell,类型为xlsx
                    showMenu: true,
                    success: (response) => { 
    
                    },
                    fail: (err) => { 
                        console.log(err)
                        this.toast('文件下载成功,打开失败,请手动打开')
                    }
                })
                },
                fail: (err) => { 
                    this.toast('文件保存失败')
                }
            })
        } else { 
                this.toast('文件下载失败')
            }
        },
      fail: (err) => { 
            this.toast('文件为空,下载失败')
       }
    })

    原文作者:勤奋的搬砖工人
    原文地址: https://blog.csdn.net/qq_38751315/article/details/118727154
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞