uniApp 使用uni.openDocument(object)预览pdf、excel、word等文件

uniApp 使用uni.openDocument(object)预览pdf、excel、word等文件

1.实现思路:

这里咱们直接用的uniapp官方提供的uni.downloadFile方法调用手机第三方能打开文件的工具,比如wps等(ps:这里实现的是APP文件预览)。

2. 直接上代码(可直接复制)

		//文件预览
		 prefile(e){
			 let that = this
			 let url = that.$config.fileUrl+e;
			  uni.downloadFile({
			            url: url,
			            success: function (res) {
						   let filepathss=plus.io.convertLocalFileSystemURL(res.tempFilePath);
			              setTimeout(
			                () =>
			                  uni.openDocument({
			                    filePath: filepathss,
			                    showMenu: false,
			                    success: function () {
			                      console.log("打开文档成功");
			                    },
			                    fail: function () {
			                      uni.showToast({
			                        title: '暂不支持此类型',
			                        duration: 2000,
			                        icon: "none",
			                      });
			                    }
			                  }),
			                1000
			              );
			            },
			            fail: function (res) {
			              console.log(res); //失败
			            }
			          });
		 }

3.注意事项

1.文件路径(url)必须是浏览器能直接访问的文件。比如:http://xx.cc.com/images/abc.xlsx 这种格式。 最开始我是用的后台给的接口 file/dowload?fileId=112334 这种形式的路径,调用 uni.openDocument 是失败的,原因可能是无法识别文件类型。
2.注意代码中
let filepathss=plus.io.convertLocalFileSystemURL(res.tempFilePath);
这行代码是获取文件在手机中的绝对路径。

例如:在这里插入图片描述

  • 6
    点赞
  • 45
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
如果您不想使用 `uni.openDocument` API 打开文件,您可以考虑使用其他方式打开文件,比如使用第三方插件或者自定义组件等。 以下是两个示例: 1. 使用第三方插件: 可以使用 uni-app 社区中的一些第三方插件来实现打开文件的功能,例如 `uni-file-picker` 插件。这个插件可以选择文件并返回文件的本地路径,您可以使用这个路径来打开文件。 安装插件: ``` npm install uni-file-picker --save ``` 使用插件: ```javascript import filePicker from 'uni-file-picker' // 选择文件 filePicker.chooseFile({ success: (res) => { // res.tempFilePaths 为文件的本地临时路径 // 这里可以使用自己的方式打开文件 } }) ``` 2. 自定义组件: 您可以自定义一个组件来实现打开文件的功能。在组件中,可以使用 `wx.chooseMessageFile` API 选择文件并返回文件的临时路径,然后使用 `wx.openDocument` API 打开文件。 组件示例: ```html <template> <button @click="openFile">打开文件</button> </template> <script> export default { methods: { openFile() { wx.chooseMessageFile({ count: 1, type: 'file', success: (res) => { wx.openDocument({ filePath: res.tempFiles[0].path, fileType: 'txt', success: () => { console.log('打开文件成功') }, fail: () => { console.log('打开文件失败') } }) }, fail: () => { console.log('选择文件失败') } }) } } } </script> ``` 注意:在使用 `wx.chooseMessageFile` 和 `wx.openDocument` API 时,需要将 `type` 和 `fileType` 参数设置为要打开的文件类型,这里以打开 txt 文件为例,需要将类型设置为 `file`,文件类型设置为 `txt`。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值