uniapp下载文件到本地兼容h5和安卓
时间: 2025-04-06 07:06:45 浏览: 103
### UniApp 文件下载兼容 H5 和 Android 的实现方式
在 UniApp 中实现文件下载功能时,需考虑不同平台的特性差异。以下是针对 H5 和 Android 平台的具体实现方案。
#### 1. **H5 平台**
对于 H5 平台,可以利用浏览器原生能力 `window.open` 或者创建 `<a>` 标签来触发文件下载操作。这种方式简单高效,适用于大多数场景。
```javascript
function downloadFileForH5(url) {
const link = document.createElement('a');
link.href = url;
link.download = 'file'; // 设置默认文件名
document.body.appendChild(link);
link.click();
document.body.removeChild(link); // 清理临时节点
}
```
此方法通过动态创建 `<a>` 标签并模拟点击事件完成文件下载[^1]。
#### 2. **Android 平台**
在 Android 平台上,由于无法直接使用 HTML 原生标签的方式,需要借助 UniApp 提供的 API 来处理文件下载逻辑。具体可以通过 `uni.downloadFile` 方法实现:
```javascript
function downloadFileForAndroid(url, filePath) {
uni.downloadFile({
url: url,
success(res) {
if (res.statusCode === 200) {
console.log('下载成功', res.tempFilePath);
// 将临时路径保存至指定位置(仅限 Android)
plus.io.resolveLocalFileSystemURL(plus.android.getApplicationContext().getFilesDir(), function(entry) {
entry.getFile(filePath, { create: true }, function(fileEntry) {
fileEntry.createWriter(function(writer) {
writer.write(plus.stream.convertBlobToBase64(res.tempFilePath));
writer.onwriteend = function() {
console.log('写入文件成功');
};
});
});
});
}
},
fail(err) {
console.error('下载失败:', err);
}
});
}
```
上述代码片段展示了如何通过 `uni.downloadFile` 完成文件下载,并将其存储到设备上的特定目录中[^3]。
#### 3. **跨平台统一解决方案**
为了使代码更加通用化,在实际开发过程中可封装一个函数用于判断当前运行环境,并分别调用对应的方法:
```javascript
function crossPlatformDownload(url, androidPath) {
if (/h5/.test(process.env.VUE_APP_PLATFORM)) {
downloadFileForH5(url);
} else if (/android/.test(process.env.UNI_PLATFORM)) {
downloadFileForAndroid(url, androidPath);
} else {
console.warn('暂不支持该平台下的文件下载');
}
}
// 调用示例
crossPlatformDownload('https://example.com/file.pdf', '/downloaded_files/example.pdf');
```
以上代码实现了基于平台检测的功能分发机制,从而达到一次编写多端适配的效果[^4]。
---
###
阅读全文
相关推荐
















