在webview页面的onLoad中使用uni.downloadFile和uni.openDocument打开pdf文档,在app端和小程序端没有问题可以正常打开,可是h5端不行,报错了The requested URL was not found on this server。 于是找了很久,最后使用了pdf.js得以解决。步骤如下:
- 下载pdf.js的文件夹到项目根目录中
- 在webview的onLoad中
onLoad(async (option) => {
// #ifdef H5
data.weburl = '/hybrid/html/web/viewer.html?file='+ encodeURIComponent(option.url)
// #endif
// #ifdef APP-PLUS || MP-WEIXIN
const downloadTask = uni.downloadFile({
url: option.url,
filePath: option.name ? wx.env.USER_DATA_PATH + "/" + `${option.name}.docx` : '',
success: function(res) {
//判断是否有传过来文件名
const filePath = res.filePath ? res.filePath : res.tempFilePath
uni.openDocument({
filePath: filePath,
success: function(res) {
console.log('打开PDF文档成功')
}
})
}
})
downloadTask.onProgressUpdate((res) => {
uni.showLoading({
title: '加载中',
success: function(res) {
uni.hideLoading();
}
});
})
// #endif
})
/hybrid/html/web/viewer.html是pdf.js的路径,option.url是从后端获取的pdf路径 pdf.js的文件可以去这里下载[pdf.js官网](开始 - PDF.js 中文文档 (gitcode.host)) 如果官网的文件不能解决你的问题,可以参考[这个](uniapp 使用PDF.js实现在线预览 - 掘金 (juejin.cn)),我的是uniapp vue3,现在解决了