版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhuxiongyin/article/details/81065165
简要:wx.downloadFile(OBJECT)下载文件资源到本地,客户端直接发起一个 HTTP GET 请求,返回文件的本地临时路径。wx.openDocument(OBJECT)新开页面打开文档,支持格式:doc, xls, ppt, pdf, docx, xlsx, pptx。
调用wx.downloadFile下载文件,success回调函数内部,再调用wx.openDocument打开并预览下载文档。
注:如需持久保存,需在主动调用 wx.saveFile,才能在小程序下次启动时访问得到。 注:请在 header 中指定合理的 Content-Type 字段,以保证客户端正确处理文件。
若有不明请到:小程序开发文档->
<view data-url="这是文档下载地址" data-type="pdf" catchtap='downloadFile'></view>
/**
* 下载文件并预览
*/
downloadFile: function(e) {
console.log(e);
let type = e.currentTarget.dataset.type;
let url = e.currentTarget.dataset.url;
switch (type) {
case "pdf":
url += 'pdf';
break;
case "word":
url += 'docx';
break;
case "excel":
url += 'xlsx';
break;
default:
url += 'pptx';
break;
}
wx.downloadFile({
url: url,
header: {},
success: function(res) {
var filePath = res.tempFilePath;
console.log(filePath);
wx.openDocument({
filePath: filePath,
success: function(res) {
console.log('打开文档成功')
},
fail: function(res) {
console.log(res);
},
complete: function(res) {
console.log(res);
}
})
},
fail: function(res) {
console.log('文件下载失败');
},
complete: function(res) {},
})
}