效果如下
1747190213779.png
点击此按钮,能下载二进制流
具体实现
1、使用downloadFile 获取本地缓存路径
wx.downloadFile({
url: apiUrl, //仅为示例,并非真实的资源
header:{
token:“你的token”
},
success (res) {
consle.log(res)
}
})
2 、使用saveFile 得到本地存储路径
const fx = wx.getFileSystemManager()
fx.saveFile({
tempFilePath:res.tempFilePath,
filePath:`${wx.env.USER_DATA_PATH}/wtdownload/test.png`,
success:(res)=>{
console.log(res)
}
})
3 使用saveImageToPhotosAlbum将saveFile 获取的路径保存到本地相册
*注意 :此函数需要申请用户隐藏权限
wx.saveImageToPhotosAlbum({
filePath:res.savedFilePath,
success:(res) =>{
wx.showToast({
title: '文件下载成功!',
icon:'none'
})
},
}
})
4 使用wx.openDocument 保存文档
文档使用openDocument 进行预览,用户手动保存
wx.openDocument({
filePath: res.savedFilePath,
showMenu:true,
success: (res)=> {
console.log('打开文档成功')
}
})
5、完整代码
wx.downloadFile({
url: apiUrl, //仅为示例,并非真实的资源
header:{
token:token
},
success (res) {
const fx = wx.getFileSystemManager()
let disposition =res.header['Content-Disposition']
let filename = disposition.split(';')[1].split('filename=')[1]
let isExist = false // 判断当前目录是否存在
try{
fx.accessSync(`${wx.env.USER_DATA_PATH}/wtdownload`)
isExist = true
}catch{}
if(!isExist){
try{
fx.mkdirSync(`${wx.env.USER_DATA_PATH}/wtdownload`,true)
isExist = true
}catch{}
}
fx.saveFile({
tempFilePath:res.tempFilePath,
filePath:`${wx.env.USER_DATA_PATH}/wtdownload/${filename}`,
success:(res)=>{
if(res.errMsg==='saveFile:ok'){
// console.log('临时文件保存成功')
wx.saveImageToPhotosAlbum({
filePath:res.savedFilePath,
success:(res) =>{
wx.showToast({
title: '文件下载成功!',
icon:'none'
})
},
fail:(err)=>{
// 为了兼容用户保存相册隐私权限不能够调用
wx.openDocument({
filePath: res.savedFilePath,
showMenu:true,
success: (res)=> {
console.log('打开文档成功')
}
})
}
})
}
},
fail:(err)=>{
}
})
}
})













网友评论