uniapp H5如何实现文件下载功能
在uniapp开发的H5页面中,如何实现文件下载功能?尝试过使用uni.downloadFile但下载后找不到文件,也测试过创建a标签触发点击,但在部分安卓浏览器中无效。请问有没有兼容性较好的解决方案?需要支持PDF、图片等常见格式下载,且能提示用户下载进度或完成状态。
2 回复
使用uni.downloadFile下载文件,再配合uni.saveFile保存到本地。注意H5端需浏览器支持,部分浏览器可能限制自动保存,可提示用户手动保存下载的文件。
在uni-app H5端实现文件下载,可以通过以下几种方式:
1. 使用 uni.downloadFile + uni.saveFile(推荐)
// 下载文件到本地
uni.downloadFile({
url: 'https://example.com/file.pdf',
success: (res) => {
if (res.statusCode === 200) {
uni.saveFile({
tempFilePath: res.tempFilePath,
success: (saveRes) => {
uni.showToast({
title: '下载成功',
icon: 'success'
});
console.log('文件保存路径:', saveRes.savedFilePath);
},
fail: (err) => {
uni.showToast({
title: '保存失败',
icon: 'none'
});
}
});
}
},
fail: (error) => {
uni.showToast({
title: '下载失败',
icon: 'none'
});
}
});
2. 使用 a 标签直接下载(简单文件)
// 创建隐藏的a标签触发下载
function downloadFile(url, filename) {
const link = document.createElement('a');
link.href = url;
link.download = filename || 'download';
link.style.display = 'none';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
// 使用示例
downloadFile('https://example.com/file.pdf', 'document.pdf');
3. 处理跨域文件下载
// 对于跨域文件,可能需要后端配合设置CORS
uni.downloadFile({
url: 'https://other-domain.com/file.pdf',
header: {
// 添加必要的请求头
},
success: (res) => {
// 处理下载成功
}
});
4. 完整示例代码
export default {
methods: {
// 下载文件方法
downloadFile(fileUrl, fileName) {
// 检查运行环境
if (uni.getSystemInfoSync().platform === 'h5') {
// H5环境使用a标签下载
const link = document.createElement('a');
link.href = fileUrl;
link.download = fileName;
link.style.display = 'none';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
} else {
// 其他平台使用uni.downloadFile
uni.downloadFile({
url: fileUrl,
success: (res) => {
if (res.statusCode === 200) {
uni.saveFile({
tempFilePath: res.tempFilePath,
success: () => {
uni.showToast({ title: '下载成功', icon: 'success' });
}
});
}
}
});
}
}
}
}
注意事项:
- 文件路径:确保下载链接是可访问的
- 跨域问题:H5下载可能受CORS限制
- 文件类型:某些浏览器可能限制特定文件类型的下载
- 用户体验:建议添加下载进度提示
选择哪种方式取决于你的具体需求和文件来源。对于简单的文件下载,使用a标签更直接;对于需要更多控制的场景,使用uni.downloadFile更合适。

