uniapp 开发微信小程序如何下载文件(zip压缩文件,pdf,图片,视频等)
最近在开发一款微信小程序 ,需要下载 zip 文件到本地,但下载成功后,文件存储位置却不知道。下面给出个解决方案:让系统自己打开文件。
下面直接贴出下载功能的代码。
//data_url为需下载文件的网络地址
downloadClick(data_url){
if (!data_url){
uni.showToast({
title: '缺少下载地址',
icon: 'none',
duration: 2000
});
return;
}
console.log(data_url)
const fs = uni.getFileSystemManager();
console.log('====', 111)
// 使用 uni.getFileSystemManager() 保存文件
uni.downloadFile({
url: data_url,
success: (downloadRes) => {
console.log('====',downloadRes)
if (downloadRes.statusCode === 200){
const isImage = /\.(jpg|jpeg|png|gif|webp)$/.test(data_url);
const isVideo = /\.(mp4|mov|avi)$/.test(data_url);
if (isImage || isVideo) {
// 图片/视频优先保存到相册
uni.saveImageToPhotosAlbum({
filePath: downloadRes.tempFilePath,
success: () => {
uni.showToast({ title: `已保存到相册`, icon: 'success' });
}
});
} else {
// 其他文件保存到本地
const fileTypeExt = data_url.split('.').pop().toLowerCase();
const destPath = `${wx.env.USER_DATA_PATH}/`+Date.now() + '.' + fileTypeExt; // 确保带后缀
fs.saveFile({
tempFilePath: downloadRes.tempFilePath,
filePath: destPath,
success: (res) => {
console.log(res)
uni.showToast({
title: '保存成功',
icon: 'success',
duration: 2000
});
uni.openDocument({
filePath: res.savedFilePath,
showMenu: true,
})
}
});
}
}
},
fail: (err) => {
console.error('下载失败:', err);
}
});
}