1.项目需求:点击下面图片所示,请求服务器获取PDF地址
2.获取到pdf地址后保存到本地,下次打开无需在请求
公分三个步骤
1.使用wx.downloadFile 微信downloadFile
2.使用 wx.saveFile 微信saveFile
3.wx.openDocument 微信openDocument
downloadFile(e) {
let {pathId} = this.data
if(!e.currentTarget.dataset.item) return;
let pdfPath = wx.getStorageSync('pdfPath') || [] //获取缓存
if(pdfPath.length > 0) {
pdfPath.forEach( item =>{
if(item.id == pathId ) {
this.setData({
pathPdf:item.url
})
}
})
}
this.setData({
speed3:true
})
this.playended()
wx.showLoading({
title: '正在加载中',
})
let that = this
let {pathPdf} = that.data
if(pathPdf) { //判断缓存中是否有该地址
console.log('本地获取地址成功')
wx.openDocument({
filePath:pathPdf,
fileType: 'pdf',
showMenu:true, //打开PDF会在右上角有三点可以下载或浏览器打开等功能
success :function (res) {
wx.hideLoading()
},
fail: function (error) {
wx.showToast({
title: '打开文件失败',
icon: 'none'
})
let arr = pdfPath.filter( item =>item.id != pathPdf ) //如果报错,就删除掉该地址,从新在请求方法,这样防范该文件失效
that.setData({
pathPdf:''
})
wx.setStorageSync('pdfPath', arr)
that.downloadFile()
}
})
} else {
console.log('这里是第一次打开该文件,进行下载')
wx.downloadFile({
url: e.currentTarget.dataset.item,
success (res) {
// 只要服务器有响应数据,就会把响应内容写入文件并进入 success 回调,业务需要自行判断是否下载到了想要的内容
if (res.statusCode === 200) {
let path = res.tempFilePath
let path1 = path.split("//")[1]
let filePath = wx.env.USER_DATA_PATH+'//'+path1
//这是将需要保存的地址更改下,否则会报错【地址:http://usr//tmp/4ZbcMpMayOG667c7da7c1759e64fb7cfdb7dc0baac45.pdf】
wx.saveFile({
tempFilePath: path,
filePath:filePath,
success: function ( res) {
let savedFilePath = res.savedFilePath // 获取到文件下载保存到本地的地址
that.setData({
pathPdf:savedFilePath
})
let obj ={
id:pathId,
url:savedFilePath,
}
let item = pdfPath.filter( item => item.id == pathId ) //判断缓存中是否存在该地址
if(item.length<1) {
pdfPath.push(obj)
}
wx.setStorageSync('pdfPath', pdfPath) //将数据存入缓存中
wx.openDocument({
filePath:savedFilePath,
showMenu:true,
success :function (res) {
wx.hideLoading()
},
fail:function ( error) {
wx.showToast({
title: '打开文件失败',
icon: 'none'
})
}
})
},
fail: function ( error ){
wx.showToast({
title: '文件下载失败',
icon: 'none'
})
}
})
}
}
})
}
},