WeChat applet to open PDF, word and other file previews

        Recently, when using uniapp to develop WeChat applets, I encountered the need to open PDF file previews on the applet. The implementation of using native WeChat applets is similar to this. The general implementation code is as follows:

// 下载文件到本地,下载成功后会返回临时文件路径
uni.downloadFile({
    url: "文件地址",
    success: function (res) {
        let filePath = res.tempFilePath;   // 下载成功后返回的临时文件路径

        // 打开临时文件
        uni.openDocument({
            filePath: filePath,
            showMenu: true,
            success: function (res) {
                console.log('打开文档成功');
            }
        });
    },
    fail: (err) => {
        // 处理下载失败的情况
    }
});

        Two APIs are mainly used here: uni.downloadFile( ) and uni.openDocument( ), the functions of these two APIs are as follows:

  1. uni.downloadFile( ): Initiate a request to download the resource to the local, and return the local temporary path of the file after the request is successful. The temporary path is only available during this startup. If you need to save it persistently, you must actively call uni.saveFile to save it. Accessed the next time the application is launched . , to be used on the WeChat applet, a whitelist needs to be configured. Official website API documentation: uni.uploadFile(OBJECT) | uni-app official website
  2. uni.openDocument( ): open a document on a new page, supported formats: doc, xls, ppt, pdf, docx, xlsx, pptx. Official website API documentation: uni.saveFile(OBJECT) @savefile | uni-app official website

Guess you like

Origin blog.csdn.net/m0_60312580/article/details/131322499