廢話不多說直接上代碼吧
之前搜了一大堆有的沒的,最終還是小伙伴巴拉文檔一起找到的方案(離不開小伙伴的幫助,自己總?cè)菀紫萑胨谰郑诖锁Q謝 疾風(fēng)李青?。?/p>
想起個事:一定要給這些路徑的域名配到相應(yīng)的開發(fā)管理上,其他平臺不過多贅述了
首先是預(yù)覽,由于我這里是uni-app框架開發(fā)三端,所以展示內(nèi)容開頭以uni為主:
如果你的dpf是鏈接形式 形如:https:// ,那么下面方案適合你(該方案,是小程序中的window.open的實現(xiàn)。)
支付寶不同機(jī)型 調(diào)用uni.downloadFile 發(fā)現(xiàn)會發(fā)現(xiàn)有多種形式的文件路徑,因此條件編譯一下(純他么坑爹)
const times = new Date().getTime();
let userPath = '';
// #ifdef MP-ALIPAY
userPath = my.env.USER_DATA_PATH;
// #endif
// #ifdef MP-WEIXIN
userPath = wx.env.USER_DATA_PATH;
// #endif
// #ifdef MP-BAIDU
userPath = swan.env.USER_DATA_PATH;
// #endif
let filePath = userPath + '/' + times + '.pdf';
export default (url) => {
uni.downloadFile({ // 下載
url, // 服務(wù)器上的pdf地址
filePath,
success: (res) => {
let openDocumentPath = filePath;
// #ifdef MP-ALIPAY
openDocumentPath = res.tempFilePath || res.filePath || filePath;
// #endif
uni.openDocument({
fileType: 'pdf',
showMenu: true,
filePath: openDocumentPath,
success: () => {
console.log('打開PDF成功')
},
fail: (err) => {
uni.showToast({
title: '打開文檔失敗,請重試!'
})
}
})
}
})
}
如果你的鏈接是base64,那么這個方案適合你
const times = new Date().getTime();
let userPath = '';
// #ifdef MP-ALIPAY
userPath = my.env.USER_DATA_PATH;
// #endif
// #ifdef MP-WEIXIN
userPath = wx.env.USER_DATA_PATH;
// #endif
// #ifdef MP-BAIDU
userPath = swan.env.USER_DATA_PATH;
// #endif
let filePath = userPath + '/' + times + '.pdf';
export default (data) => {
const fileSystemManager = uni.getFileSystemManager();
fileSystemManager.writeFile({
//保存本地臨時路徑
filePath,
data,
encoding: 'base64',
success: (res) => {
uni.openDocument({
fileType: 'pdf',
showMenu: true,
filePath,
success: function (res) {
console.log('打開PDF成功')
},
fail(err) {
uni.showToast({
title: '打開文檔失敗,請重試!'
})
}
})
}
})
}
總結(jié):
主要思路還是通過不同的api將文件先下載到小程序存儲,通過uni.openDocument去打開,
- 配置相應(yīng)服務(wù)器域名。
- 使用對應(yīng)小程序api預(yù)覽。
下載:
僅微信安卓端可實現(xiàn),
uni.openDocument 打開 showMenu: true,
其實就是微信預(yù)覽的時候,開啟menu,通過右上角的三個點點擊后保存到手機(jī)。
看到其他大牛給到的方案,都不是很完美,貼個鏈接吧。
微信小程序下載文件,保存文件功能總結(jié)
-
通過base64或pdf鏈接 轉(zhuǎn) png后,再fileSystemManager.saveFile API保存文件為圖片格式;
下載,完事讓用戶自己改后綴。 -
先使用下載文件api把文件下載下來,再使用wx.openDocument() 打開文件里面加上showMenu字段,然后就可以看到在打開的文件右上角出現(xiàn)了,
? ios表現(xiàn):ios點擊之后會有發(fā)送給朋友的選項,選擇分享給朋友之后就可以把文件直接發(fā)送給對方了,然后你就可以在聊天記錄里面拿到這個文件;文章來源:http://www.zghlxwxcb.cn/news/detail-609617.html
這兩種方式 都不是很完美,所以 小程序端暫時不建議提供下載功能,
除非給個鏈接 讓用戶沾出去從瀏覽器下載。文章來源地址http://www.zghlxwxcb.cn/news/detail-609617.html
到了這里,關(guān)于uni-app 微信小程序 支付寶小程序(alipay) 百度小程序(baidu),預(yù)覽pdf(鏈接和base64) 及下載(僅微信),window.open uni.downloadFile的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!