需求点:使用wx.downloadFile()、wx.openDocument()两个API配合,下载预览文件并分享
问题:wx.downloadFile()的 url 参数填入的路径中带有中文,请求API时,文件路径中的中文被转码了,导致下载不了正确的文件,tempFilePath返回的是后缀.bin的文件,wx.openDocument()无法打开预览
配合使用wx.FileSystemManager()的几个API,保存重命名后可以打开预览了,解决思路如下:
// 创建存放目录
createCatalog (e) {
const rootPath = wx.env.USER_DATA_PATH
const cachePath = rootPath + '/openFileCache'
const manage = wx.getFileSystemManager()
let newFileName = ''
let fileType = ''
let downLoadPath = e.currentTarget.dataset.path
if (e.currentTarget.dataset.path.indexOf('.xlsx') !== -1) {
fileType = '.xlsx'
} else if (e.currentTarget.dataset.path.indexOf('.xls') !== -1) {
fileType = '.xls'
} else if (e.currentTarget.dataset.path.indexOf('.pdf') !== -1) {
fileType = '.pdf'
}
newFileName = this.data.recordData[e.currentTarget.dataset.idx].title + fileType
// 判断是否已存在自定义目录
manage.access({
path: cachePath,
success: res => {
console.log(res)
let readdir = manage.readdirSync(cachePath)
console.log(readdir)
for (let path of readdir) {
manage.unlinkSync(cachePath + '/' + path)
}
this.openFileEv(cachePath, newFileName, downLoadPath)
},
fail: err => {
console.log(err)
// 新建自定义目录
manage.mkdir({
dirPath: cachePath,
recursive: true,
success: res => {
console.log('创建成功')
this.openFileEv(cachePath, newFileName, downLoadPath)
},
fail: err => {
console.log('创建失败')
}
})
}
})
},
// 打开文件
openFileEv (cachePath, newFileName, downLoadPath) {
const manage = wx.getFileSystemManager()
wx.showLoading({
title: '加载中',
mask: true,
success: function () {
wx.downloadFile({
// 示例 url,并非真实存在
url: downLoadPath,
success: function (res) {
if (res.statusCode === 200) {
wx.hideLoading()
manage.saveFileSync(res.tempFilePath, cachePath + '/' + newFileName)
// 打开文档
wx.openDocument({
filePath: cachePath + '/' + newFileName,
showMenu: true,
success: function (res) {
console.log('打开文档成功')
},
fail: function () {
console.log('打开失败')
}
})
}
}
})
}
})
}