小程序文件下载并写入存储并以非临时文件名打开
1.接口调整基础
盼星星,盼月亮,终于盼来了微信小程序SaveFile
接口的调整,以前10M
限制的时代一去不复返了。
以前超过10M
的文件想要打开,只可以通过临时文件的方式,打开文件前需要判断文件大小,只有小于10M的文件才可以写入存储,以非临时文件的形式打开。
文件上传具体部分代码解析,请参见我的另一篇博客:https://www.cnblogs.com/masterchd/p/12319440.html
3.文件下载
此部分包含三个功能点
文件下载和进度监听
downFile(e) {
this.clv(); //清理缓存部分代码
var fdetail = e.currentTarget.dataset.detail;
var iscloud = this.data.cloud;
var downloadTask = null;//下载进度监听器
downloadTask = wx.cloud.downloadFile({
fileID: fdetail.fileurl,success(res) {
var finfo = wx.getFileInfo({
filePath: res.tempFilePath,success: f => {
wx.getFileSystemManager().saveFile({
tempFilePath: res.tempFilePath,filePath: `${wx.env.USER_DATA_PATH}` + "/" + fdetail.filename,})
wx.showModal({
title: '是否打开文件',content: '',success(ans) {
if (ans.confirm) {
wx.openDocument({
filePath: wx.env.USER_DATA_PATH + "/" + fdetail.filename,})
}
}
})
}
})
}
})
downloadTask.onProgressUpdate((res) => {
this.setData({
jindu: res.progress
})
})
},
文件缓存清理
clv() {
wx.getSavedFileList({ // 获取文件列表
success(res) {
res.fileList.forEach((val,key) => { // 遍历文件列表里的数据
// 删除存储的垃圾数据
wx.removeSavedFile({
filePath: val.filePath
});
})
}
})
},
改部分代码可以写入saveFile
的fail
回调中,并在该部分代码成功回调后,再次调用saveFile
完成文件写入。
4.整体效果展示
参考
1.开源项目地址(代码):https://gitee.com/Kindear/yamako_procedure
2.微信社区更新公告:https://developers.weixin.qq.com/community/develop/doc/000e64a2010bd8da540bf44085e401