uniApp uses uni.openDocument(object) to preview pdf, excel, word and other files

uniApp uses uni.openDocument(object) to preview pdf, excel, word and other files

1. Implementation ideas:

Here we directly use the uni.downloadFile method officially provided by uniapp to call third-party tools that can open files on the mobile phone, such as wps, etc. (ps: here is the APP file preview).

2. Directly upload the code (can be copied directly)

		//文件预览
		 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. Precautions

1. The file path (url) must be a file that the browser can directly access. For example: http://xx.cc.com/images/abc.xlsx this format. At the beginning, I used the interface file/dowload?fileId=112334 provided by the background. The call to uni.openDocument failed. The reason may be that the file type cannot be recognized.
2. Note that in the code
let filepathss=plus.io.convertLocalFileSystemURL(res.tempFilePath);
this line of code is to obtain the absolute path of the file in the phone.

For example:insert image description here

Guess you like

Origin blog.csdn.net/weixin_41377835/article/details/126890525