1.下载预览文件;
src是网络的PPT链接;wx.openDocument的文件只能是临时文件,所以需要先用wx.downloadFile下载得到一个临时文件,再用wx.openDocument预览打开这个临时文件;
wx.openDocument会是一个新页面打开文件;想要显示右上角的菜单,需要showMenu设置为true;右上角菜单可以做下面这些操作;
wx.openDocument这里fileType这个是文件类型,可以预览下面这些类型;
但是PC端不支持wx.openDocument打开文档;
downLoad(src) {
let _that = this;
wx.downloadFile({
url: src,
success: function(res) {
wx.openDocument({
filePath:res.tempFilePath, //临时文件
fileType: 'pptx',
showMenu: true,
success: function(res) {
console.log(res);
}
});
},
fail(res) {
console.log("fail",res)
uni.showToast({
title: res.errMsg,
duration: 5000
});
}
})
},
这种方式有一个问题,就是打开的文件名是很长一段的临时文件名;
2.解决文件名;
在wx.downloadFile添加filePath(指定文件下载后存储的路径,自定义存储本地的路径);
decodeURIComponent(src)是转义src的中文;
wx.openDocument里面这个filePath就需要用指定的文件路径
downLoad(src) {
let file = this.getFilePathName(decodeURIComponent(src));
console.log(file); //会打印最后一个/后面的文件名称,比如我的链接是https://www.wenjian.com/姐姐们.pptx;就会打印姐姐们.pptx;
let _that = this;
wx.downloadFile({
url: src,
filePath:wx.env.USER_DATA_PATH+'/'+file,
success: function(res) {
wx.openDocument({
filePath: res.filePath,//指定的文件路径
fileType: 'pptx',
showMenu: true,
success: function(res) {
console.log(res);
}
});
},
fail(res) {
console.log("fail",res)
uni.showToast({
title: res.errMsg,
duration: 5000
});
}
})
},
getFilePathName(path) {
let pos1 = path.lastIndexOf('/');
let pos2 = path.lastIndexOf('\\');
let position = Math.max(pos1,pos2);
console.log(position);
if(position<0) return path;
else return path.substring(position+1);
}
处理结果:
3.在电脑端预览文件;
这个官方显示是保存文件系统的文件到用户磁盘,仅在 PC 端支持;
但是其实只有预览功能,而且只能预览,不能显示右上角的菜单;
downLoad(src) {
wx.saveFileToDisk({
filePath: src,
success: function(res) {
console.log(res);
}
})
};