小程序 - 文件预览
小程序文件预览
/** 预览 - txt文本 */viewTxt(path) {let fs = wx.getFileSystemManager();let _this = this;fs.readFile({filePath: path,encoding: "utf8",position: 0,success(res) {_this.setData({setNoRefresh: true});wx.navigateTo({url: `/pages/view-txt/view-txt?content=${res.data}`});},fail(res) {showToast("文件打开失败");console.error(res);}});},/** 预览 - 文件 */viewFile(path, type) {wx.openDocument({filePath: path,// 文档类型fileType: type,success(res) {console.log("打开文档成功", res);},complete(err) {console.log("打开文档成功2", err);},fail() {showToast("文件打开失败");}});},/** 在线预览文档 */openDocument(e) {let { item } = e.detail;let _this = this;wx.downloadFile({url: item.materialUrl,success(res) {const path = res.tempFilePath;if (item.materialUrl.endsWith(".txt")) {_this.viewTxt(path);} else {_this.viewFile(path, item.type);}},fail(err) {if (err.errMsg.includes("downloadFile:fail file data is empty")) {wx.navigateTo({url: `/pages/view-txt/view-txt?content=`});} else {showToast("文件打开失败");}}});},
注意事项
- wx.openDocument方法 ios 不支持打开txt文本,需单单独处理
- wx.downloadFile ios下载空文件 报错:downloadFile:fail file data is empty, 需根据fail报错信息单独处理