闽公网安备 35020302035485号
在下载之前,我们得先调用接口获取文件下载的url :
然后通过wx.downloadFile将下载文件资源到本地:
wx.downloadFile({
url: res.data.url,
success: function (res) {
console.log('数据',res);
}
})

// 堆代码 duidaima.com
// 预览和下载
wx.downloadFile({
url: res.data.url,
success: function (res) {
const filePath = res.tempFilePath // 临时文件路径
wx.openDocument({
filePath: filePath,
showMenu: true // 预览文件右上方的...
})
}
})
到这里文件的预览和存储就完成了,你可以显示的看到文件的存储位置。
const downloadTask = wx.downloadFile({
url: res.data.url,
success: function (res) {
// progress进度100时触发success
}
})
downloadTask.onProgressUpdate((res) => {
console.log('下载进度', res.progress)
console.log('已经下载的数据长度', res.totalBytesWritten)
console.log('预期需要下载的数据总长度', res.totalBytesExpectedToWrite)
})


本地临时文件只能通过调用特定接口产生,不能直接写入内容。本地临时文件产生后,仅在当前生命周期内保证有效,重启之后不一定可用。如果需要保证在下次启动时无需下载,可通过 FileSystemManager.saveFile() 或 FileSystemManager.copyFile() 接口把本地临时文件转换成本地缓存文件或本地用户文件。
在上文中我们将wx.downloadFile返回的临时路径当作中转,调用wx.openDocument来保存文件,这是一种方法,还有一种就是操作文件系统API,对临时文件进行移动、保存、复制等操作。
async downloadPdf(id) {
let that = this;
let res = await getPdfAPI(id);
// 下载文件
wx.downloadFile({
url: res.data.url,
success: async (res) => {
// 设置存储路径
let myPath = wx.env.USER_DATA_PATH + '/MyFile'
try {
// 判断文件夹是否存在
await that.fileExist(myPath)
// 存在: 保存文件到本地
await that.fileSave(res.tempFilePath, myPath).catch(err => console.log(err));
wx.showToast({
title: '保存成功',
icon: 'none'
})
} catch (e) {
// 不存在: 创建文件夹
await that.fileMkdir(myPath).catch(err => console.log(err));
// 保存文件到本地
await that.fileSave(res.tempFilePath, myPath).catch(err => console.log(err));
wx.showToast({
title: '保存成功',
icon: 'none'
})
}
}
})
},
// 保存文件
fileSave(tempFilePath, myPath) {
return new Promise(function (resolve, reject) {
const fileManager = wx.getFileSystemManager(); // 文件系统
fileManager.saveFile({
tempFilePath: tempFilePath, // 临时文件路径
filePath: myPath + '/myFileName.pdf', // 文件夹路径 + 文件名
success: function (res) {
resolve(res)
},
fail: function (err) {
reject(err)
}
})
})
},
// 创建文件夹
fileMkdir(myPath) {
return new Promise(function (resolve, reject) {
const fileManager = wx.getFileSystemManager(); // 文件系统
fileManager.mkdir({
dirPath: myPath, // 文件夹路径
success: function (mkdir) {
resolve(mkdir)
},
fail: function (mkdirerr) {
reject(mkdirerr)
}
})
})
},
// 判断文件夹是否存在
fileExist(myPath) {
return new Promise(function (resolve, reject) {
const fileManager = wx.getFileSystemManager(); // 文件系统
fileManager.access({
path: myPath, // 文件夹路径
success: function (exist) {
resolve(exist)
},
fail: function (err) {
reject(err)
}
})
})
},
注意点:3、wx.env.USER_DATA_PATH是一个字符串,表示文件系统中的用户目录路径 (本地路径)
