uniapp 如何实现文件下载功能
在uniapp中如何实现文件下载功能?我在开发时需要下载服务器上的PDF和图片文件到手机本地,但用uni.downloadFile()下载后不知道如何保存到指定目录。求完整代码示例,包括权限请求和保存路径处理,最好能兼容Android和iOS平台。另外下载进度条和失败重试机制该如何实现?
2 回复
使用 uni.downloadFile 下载文件,示例:
uni.downloadFile({
url: '文件链接',
success: (res) => {
if (res.statusCode === 200) {
uni.saveFile({
tempFilePath: res.tempFilePath
})
}
}
})
注意:需配置网络请求白名单,H5端可能受浏览器限制。
在 UniApp 中实现文件下载功能,可以使用 uni.downloadFile API 下载文件到本地临时路径,然后通过 uni.openDocument 或 uni.saveFile 进行预览或保存。以下是具体实现方法:
1. 基本下载与预览
// 下载文件并预览(适用于图片、PDF等)
uni.downloadFile({
url: 'https://example.com/file.pdf', // 替换为实际文件URL
success: (res) => {
if (res.statusCode === 200) {
// 预览文件
uni.openDocument({
filePath: res.tempFilePath,
success: () => console.log('打开文档成功')
});
}
},
fail: (err) => console.error('下载失败:', err)
});
2. 下载并保存到本地
// 下载后保存到用户设备(仅App和H5支持)
uni.downloadFile({
url: 'https://example.com/image.jpg',
success: (res) => {
uni.saveFile({
tempFilePath: res.tempFilePath,
success: (savedRes) => {
console.log('文件保存到:', savedRes.savedFilePath);
uni.showToast({ title: '保存成功' });
}
});
}
});
3. 多平台兼容处理
function downloadFile(url, fileName) {
// #ifdef APP-PLUS
// APP端使用原生下载
const dtask = plus.downloader.createDownload(url, {}, (d, status) => {
if (status === 200) {
plus.runtime.openFile(d.filename); // 自动打开文件
}
});
dtask.start();
// #endif
// #ifdef H5
// H5端创建隐藏链接下载
const link = document.createElement('a');
link.href = url;
link.download = fileName || 'download';
link.click();
// #endif
// #ifdef MP-WEIXIN
// 微信小程序使用uni.downloadFile
uni.downloadFile({
url,
success: (res) => uni.openDocument({ filePath: res.tempFilePath })
});
// #endif
}
注意事项:
- 网络请求权限:确保在
manifest.json中配置了网络请求白名单 - 文件格式限制:部分平台对打开的文件格式有限制
- 存储权限:App端保存文件需要存储权限
- 临时路径:下载的临时文件在应用关闭后可能被清理
完整示例:
<template>
<view>
<button @click="downloadPDF">下载PDF文档</button>
<button @click="downloadImage">下载图片并保存</button>
</view>
</template>
<script>
export default {
methods: {
downloadPDF() {
uni.downloadFile({
url: 'https://example.com/demo.pdf',
success: (res) => uni.openDocument({ filePath: res.tempFilePath })
});
},
downloadImage() {
uni.downloadFile({
url: 'https://example.com/photo.jpg',
success: (res) => {
uni.saveFile({
tempFilePath: res.tempFilePath,
success: (savedRes) => {
uni.showToast({ title: `已保存到: ${savedRes.savedFilePath}` });
}
});
}
});
}
}
}
</script>
根据具体需求选择合适的实现方式,注意不同平台的特性差异。

