小程序本身的api 并不能实现 文件下载到 系统,只能实现下载到小程序的临时缓存里,那么想要实现 下载与本地存储 需要用到 文件下载和本地文件系统API;具体方案如下:
1.下载文件到本地
wx.downloadFile({ url: 'https://example.com/file.pdf', // 文件URL success(res) { if (res.statusCode === 200) { // 文件临时路径 const tempFilePath = res.tempFilePath // 将文件保存到本地 saveFileToLocal(tempFilePath) } }, fail(err) { console.error('下载失败:', err) wx.showToast({ title: '下载失败', icon: 'none' }) } })
2. 保存到本地文件系统
function saveFileToLocal(tempFilePath) { wx.getFileSystemManager().saveFile({ tempFilePath: tempFilePath, success(res) { const savedFilePath = res.savedFilePath console.log('文件保存成功:', savedFilePath) // 将文件路径保存到全局数据或缓存中 wx.setStorageSync('downloadedFilePath', savedFilePath) wx.showToast({ title: '保存成功', icon: 'success' }) }, fail(err) { console.error('保存失败:', err) wx.showToast({ title: '保存失败', icon: 'none' }) } }) }
小程序文件下载与本地存储方案
要实现小程序下载文件并能在关闭小程序后仍能访问,需要使用微信小程序的文件下载和本地文件系统API。以下是完整的实现方案:
一、基础实现步骤
1. 下载文件到本地
wx.downloadFile({
url: 'https://example.com/file.pdf', // 文件URL
success(res) {
if (res.statusCode === 200) {
// 文件临时路径
const tempFilePath = res.tempFilePath
// 将文件保存到本地
saveFileToLocal(tempFilePath)
}
},
fail(err) {
console.error('下载失败:', err)
wx.showToast({
title: '下载失败',
icon: 'none'
})
}
})2. 保存到本地文件系统
function saveFileToLocal(tempFilePath) {
wx.getFileSystemManager().saveFile({
tempFilePath: tempFilePath,
success(res) {
const savedFilePath = res.savedFilePath
console.log('文件保存成功:', savedFilePath)
// 将文件路径保存到全局数据或缓存中
wx.setStorageSync('downloadedFilePath', savedFilePath)
wx.showToast({
title: '保存成功',
icon: 'success'
})
},
fail(err) {
console.error('保存失败:', err)
wx.showToast({
title: '保存失败',
icon: 'none'
})
}
})
}二、完整实现方案
1. 封装下载方法
// utils/fileDownload.js
const downloadAndSaveFile = (url, fileName) => {
return new Promise((resolve, reject) => {
wx.showLoading({ title: '下载中...' })
wx.downloadFile({
url,
success(res) {
if (res.statusCode === 200) {
const fs = wx.getFileSystemManager()
fs.saveFile({
tempFilePath: res.tempFilePath,
filePath: `${wx.env.USER_DATA_PATH}/${fileName || Date.now()}`,
success(savedRes) {
wx.hideLoading()
resolve(savedRes.savedFilePath)
wx.showToast({ title: '下载成功', icon: 'success' })
},
fail: reject
})
} else {
reject(new Error('下载失败'))
}
},
fail: reject
})
})
}2. 在页面中使用
Page({
downloadFile() {
downloadAndSaveFile('https://example.com/report.pdf', '年度报告.pdf')
.then(filePath => {
// 记录文件路径
this.setData({ filePath })
// 可以保存到缓存
wx.setStorageSync('lastDownloadedFile', {
name: '年度报告.pdf',
path: filePath,
date: new Date().toLocaleString()
})
})
.catch(err => {
console.error(err)
wx.showToast({ title: '下载失败', icon: 'none' })
})
},
openFile() {
const { filePath } = this.data
if (filePath) {
wx.openDocument({
filePath,
fileType: 'pdf',
success() {
console.log('打开文档成功')
},
fail(err) {
wx.showToast({ title: '打开文件失败', icon: 'none' })
}
})
}
}
})
浙公网安备 33010602011771号