1.首先需要在小程序后台-开发设置-服务器域名 配置好下载的域名。不配置:会导致下载失败和打开文件失败;
2.pdf文件的url要确保可以浏览器直接打开。
<template><view class="pdf"><view v-for="(item,index) in pdfList" :key="index"><view>该pdf可以直接在浏览器打开</view><view style="text-align: center;color:#007AFF;" @click="openPdf(item.url)">{{item.name}}</view></view></view>
</template><script>
export default {data () {return {pdfList: [{name: '某某报告.pdf',url: 'https://push-repair.zuihuibao.cn/ACHC00DE0421FP00359D.pdf?e=1629455710&token=vuxdWg0Cy8FEDKDawxk2AJ2Mq9guC8xVHBddeMpk:wPeqcMpPZkCUIosNOSQBz4132bA='// chrome-extension://ikhdkkncnoglghljlkmcimlnlhkeamad/pdf-viewer/web/viewer.html?file=https%3A%2F%2Fpush-repair.zuihuibao.cn%2FACHC00DE0421FP00359D.pdf%3Fe%3D1629432102%26token%3DvuxdWg0Cy8FEDKDawxk2AJ2Mq9guC8xVHBddeMpk%3AJWYfdma3C84sDC2qrvTQVZTlczs%3D}]}},methods: {openPdf (pdfUrl) {// 1.pdfUrl 可以直接在浏览器打开 2.一定要在小程序后台配置该pdf的域名 让其可以下载 uni.showLoading({title: '正在打开...'})uni.downloadFile({url: pdfUrl,success: function (res) {console.log('下载的res', res)var filePath = res.tempFilePathuni.openDocument({filePath: encodeURI(filePath),// fileType: 'pdf',success: function (res) {uni.hideLoading()// uni.showToast({// title: '打开文档成功',// duration: 1500,// icon: 'none'// })console.log('打开文档成功')},fail: function (err) {uni.hideLoading()uni.showToast({title: '打开失败',duration: 1500,icon: 'none'})console.log('打开失败')}})},fail: function (err) {console.log('下载失败原因', err)uni.hideLoading()setTimeout(() => {uni.showToast({title: '下载失败',duration: 1500,icon: 'none'})}, 1500)}})}},
}
</script><style>
</style>