以下代碼兼容三端,app,h5,微信小程序,經(jīng)過(guò)個(gè)人測(cè)試
手機(jī)端有兩種方法,使用renderjs或者uniapp的api
兩者的區(qū)別文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-510988.html
- 使用renderjs的寫(xiě)法,會(huì)提示用戶(hù)是否下載文件,下載完成后用戶(hù)需要手動(dòng)點(diǎn)擊下載的文件,才會(huì)打開(kāi)文件
- 使用uniapp的api則可以直接下載并直接預(yù)覽,不需要用戶(hù)操作
- 根據(jù)場(chǎng)景需求進(jìn)行選擇即可
- ios需要注意中文名稱(chēng)的文件需要轉(zhuǎn)碼https://blog.csdn.net/weixin_45122120/article/details/107956432
<template>
<div>
<!-- #ifdef APP-PLUS -->
<button @click="test.exportPDF">預(yù)覽和下載pdf(renderjs)</button>
<button @click="exportPDF">預(yù)覽和下載pdf(uniapp api)</button>
<!-- #endif -->
<!-- #ifndef APP-PLUS -->
<button @click="exportPDF">預(yù)覽和下載pdf</button>
<!-- #endif -->
</div>
</template>
<!-- #ifdef APP-PLUS -->
<script module="test" lang="renderjs">
export default {
methods: {
exportPDF() {
const Url = "https://vkceyugu.cdn.bspapp.com/VKCEYUGU-7da443bc-353a-4224-ab27-b98917aa6c66/89d1d612-734a-4219-9110-0b21fb004d5f.pdf"
const a = document.createElement("a")
a.href = Url
a.download = "download"
a.click()
}
}
}
</script>
<!-- #endif -->
<script>
export default {
methods: {
exportPDF() {
// #ifdef H5
window.open(
"https://vkceyugu.cdn.bspapp.com/VKCEYUGU-7da443bc-353a-4224-ab27-b98917aa6c66/89d1d612-734a-4219-9110-0b21fb004d5f.pdf"
)
// #endif
// 微信下載文件需要在微信公眾平臺(tái)>開(kāi)發(fā)>開(kāi)發(fā)管理>服務(wù)器域名>downloadFile合法域名>配置白名單域名
// #ifdef MP-WEIXIN
uni.downloadFile({
url:
"https://vkceyugu.cdn.bspapp.com/VKCEYUGU-7da443bc-353a-4224-ab27-b98917aa6c66/89d1d612-734a-4219-9110-0b21fb004d5f.pdf",
success: res => {
console.log(res)
if (res.statusCode === 200) {
// 預(yù)覽pdf文件
uni.openDocument({
filePath: res.tempFilePath,
showMenu: true, // 右上角菜單,可以進(jìn)行分享保存pdf
success: function(file) {
console.log("file-success", file)
}
})
}
}
})
// #endif
// #ifdef APP-PLUS
uni.downloadFile({
url:
"https://vkceyugu.cdn.bspapp.com/VKCEYUGU-7da443bc-353a-4224-ab27-b98917aa6c66/89d1d612-734a-4219-9110-0b21fb004d5f.pdf",
success: res => {
console.log(res)
if (res.statusCode === 200) {
// 保存pdf文件至手機(jī),一般安卓端存儲(chǔ)路徑為:手機(jī)存儲(chǔ)/dcim/camera文件夾下
uni.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success: function() {
uni.showToast({
title: "文件已保存至/DCIM/CAMERA文件夾下",
icon: "none"
})
setTimeout(function() {
// 預(yù)覽pdf文件
uni.openDocument({
filePath: res.tempFilePath,
showMenu: true,
success: function(file) {
console.log("file-success", file)
}
})
}, 1500)
},
fail: function() {
uni.showToast({
title: "保存失敗,請(qǐng)稍后重試!",
icon: "none"
})
}
})
}
}
})
// #endif
}
}
}
</script>
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-510988.html
到了這里,關(guān)于uniapp實(shí)現(xiàn)h5、app、微信小程序三端pdf文件下載和預(yù)覽的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!