必须走 downloadFile → saveFile → openDocument 三步链路,因 tempFilePath 是沙盒内一次性路径,系统文档查看器无权访问;H5 需绕开该链路,用 window.location.href 下载或 web-view 预览。

不能直接用 uni.downloadFile + uni.openDocument 两步就完事——真机上基本会失败,安卓报“file not found”,iOS 静默失败,H5 根本不走这套逻辑。
为什么 uni.downloadFile 返回的 tempFilePath 不能直接打开
临时路径是沙盒内的一次性地址,系统级文档查看器无权访问:
- 安卓:
tempFilePath指向的是应用私有缓存目录(如/data/data/xxx/cache/xxx),部分厂商(华为、小米)甚至禁止跨进程读取 - iOS:沙盒隔离严格,
tempFilePath不在Document或_doc/目录下,uni.openDocument无法获得授权 - H5:
uni.downloadFile实际触发浏览器原生下载,tempFilePath是空字符串或undefined,后续调用uni.saveFile和uni.openDocument全部无效
必须走 downloadFile → saveFile → openDocument 三步链路
只有 uni.saveFile 成功后返回的 savedFilePath 才是各平台都认可的稳定路径:
- 安卓优先存到
_downloads/(无需权限,兼容 Android 10+ Scoped Storage) - iOS 必须存到
_doc/,且若文件名含中文,需用escape()编码再传给uni.openDocument - 必须在
saveFile.success回调里调uni.openDocument,不能只等downloadFile.success - 务必检查
res.statusCode === 200,否则tempFilePath可能为空或损坏
示例关键片段:
uni.downloadFile({
url: 'https://example.com/report.pdf',
success: (res) => {
if (res.statusCode === 200) {
uni.saveFile({
tempFilePath: res.tempFilePath,
success: (saveRes) => {
const filePath = saveRes.savedFilePath;
const platform = uni.getSystemInfoSync().platform;
const finalPath = platform === 'ios' ? escape(filePath) : filePath;
uni.openDocument({
filePath: finalPath,
fileType: 'pdf',
showMenu: true
});
}
});
}
}
});
H5 环境必须完全绕开 App 链路
uni.openDocument 在 H5 官方明确标注「仅 App 和小程序支持」,强行调用只会进 fail 回调且无提示:
- 下载:直接
window.location.href = url触发浏览器原生下载 - 预览 PDF:用
<web-view>加载第三方服务(如https://view.xdocin.com/view?src=+encodeURIComponent(url)),或后端代理 +pdf.js渲染 - 预览 Office 文档:同理,
<web-view>是最稳方案;pdf.js对 docx/xlsx 无效 - 不要尝试在 H5 里伪造
tempFilePath或调uni.saveFile,它们返回空或报错
容易被忽略的细节
真正上线时卡住的往往不是主流程,而是这些点:
- 服务端返回的
Content-Disposition带中文文件名时,iOSuni.openDocument会失败,建议后端改用英文名或 URL 编码 - 安卓 10+ 不再需要申请
WRITE_EXTERNAL_STORAGE权限,但路径必须落在沙盒内(_downloads/或_doc/) - 大文件(>50MB)下载时,
uni.downloadFile可能因内存不足中断,应配合progress回调做分段提示,必要时改用plus.downloader - 重复下载同一文件时,
uni.saveFile默认会覆盖,如需避免,应先用uni.getSavedFileList或plus.io.resolveLocalFileSystemURL判断是否存在


















