解决 uni.downloadFile下载mp4文件,临时路径返回.bin类型问题
function handledownloadVideo (payload) {
return new Promise((resolve) => {
let filename = payload.name.split("."); // 获取后缀名
let type = filename[filename.length- 1];
// 调用后端接口,返回流文件格式的数据
getFile(payload.id).then(res=>{
const filePath = `${wx.env.USER_DATA_PATH}/` + Date.now() + "." + type; // 临时文件路径
wx.getFileSystemManager().writeFile({
filePath: filePath,
data: res,
encoding: 'binary',
success: function() {
resolve(filePath)
},
fail: function(error) {
console.error('文件保存失败', error);
}
});
})
})
}
handledownloadVideo({name:"xxx宣传视频.mp4",fileId:"12345"})
补充
经过测试 getFileSystemManager 方式存在文件过大时报错the maximum size of the file storage limit is exceeded问题。 解决方式:
uni.downloadFile({
url: requestUrl,
header:{
responseType: 'arraybuffer',
Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7"
},
filePath: uni.env.USER_DATA_PATH + '/' + Date.now() + '.' + type,// type是文件类型
success:(response)=>{
resolve(response.filePath)
},
fail:(errr)=>{
console.log('错误信息',errr);
}
})
filePath包含-时我试着报错,所以使用时间戳
补充2
经测试多次并行调用downloadFile时可能也会报内存超出问题,解决方式: 在合适时机清空本地文件列表
export const clearFileList = ()=>{
var fs = wx.getFileSystemManager()
fs.readdir({
dirPath: wx.env.USER_DATA_PATH, // 本地用户目录
success (res) {
for (var i = 0; i < res.files.length; i++) {
if (res.files[i].split(".").length >= 2) {
// 可能会存在文件夹,导致删除报错,包含.则证明是文件
fs.unlink({
filePath: wx.env.USER_DATA_PATH + '/' + res.files[i],
success (res) {
},
fail (err) {
console.log(err)
}
})
}
}
},
fail (err) {
}
})
}