小程序中打开pdf文件(wx.downloadFile+wx.openDocument)

wx.downloadFile({}) 下载,然后 用 wx.openDocument({}) 打开文件

1、先请求到 pdf 路径网络地址,将 pdf 下载到本地

2、从本地文件上传到一个临时路径中,将本地文件删除

3、打开临时路径的文件

注意:需要在开发者管理中,配置一下downloadFile合法域名:

        微信公众平台-->开发管理-->开发设置-->downloadFile合法域名

openHandle() {
    let that = this;
    const fileExtName = ".pdf";
    const randfile = new Date().getTime() + fileExtName;
    const newPath = `${wx.env.USER_DATA_PATH}/${randfile}`;  // 定义一个临时路径
    that.deletContract();  // 将本地文件删除
    wx.downloadFile({
      url: "", // 网络文件的地址
      header: {
        "content-type": "application/pdf",
        Authorization: wx.getStorageSync("token"),
      },
      filePath: newPath,
      success: function (res) {
        const filePath = res.tempFilePath;
        wx.openDocument({
          filePath: newPath,
          showMenu: true,
          fileType: "pdf",
          success: function (res) {},
        });
      },
      fail: function (res) {
        wx.hideLoading();
      },
    });
  },
  // 删除本地文件
  deletContract() {
    try {
      let file = wx.getFileSystemManager();
      file.readdir({
        dirPath: `${wx.env.USER_DATA_PATH}`,
        success: (res) => {
          if (res.files.length > 2) {
            file.unlink({
              filePath: `${wx.env.USER_DATA_PATH}/${res.files[0]}`,
              complete: (res) => {},
            });
          }
        },
      });
    } catch (error) {}
  },

### 微信小程序 `wx.downloadFile` 文件流处理 #### 处理文件流的关键要点 当使用 `wx.downloadFile` 下载文件时,该 API 主要用于获取临时本地文件路径。对于文件流的处理,通常是在接收到服务器返回的数据后将其保存到本地临时存储中再做进一步操作。 由于微信小程序环境下的网络请求具有一定的限制条件[^1],因此在设计涉及大量或频繁下载的应用逻辑时需特别注意并发控制机制的设计: - 小程序对 `wx.downloadFile` 的并发数有限制,超过一定数量可能导致请求被中断而触发 `fail interrupted` 错误。 - 对于URL地址中的域名和端口号匹配问题也需要严格遵循规定,即如果 URL 中包含了特定端口,则安全域名设置里也要相应地带上此端口信息[^3]。 #### 实现示例:通过 wx.downloadFile 进行 PDF 文档的下载与展示 下面是一个具体的例子来说明如何利用 `wx.downloadFile` 来实现PDF文档的在线查看功能: ```javascript // 假设已知目标文件链接为 https://example.com/document.pdf const fileUrl = "https://example.com/document.pdf"; wx.downloadFile({ url: fileUrl, success(res) { if (res.statusCode === 200){ const tempFilePath = res.tempFilePath; // 使用 openDocument 方法打开 pdf 类型文件 wx.openDocument({ filePath: tempFilePath, fileType: 'pdf', showMenu: true, success() { console.log('成功打开PDF'); }, fail(err) { console.error('打开PDF失败:', err); // 提供友好的提示给用户 wx.showToast({title:"无法显示PDF"}); } }); }else{ console.warn(`HTTP状态码不是200,实际值:${res.statusCode}`); wx.showToast({title:`下载失败(${res.statusCode})`}); } }, fail(err) { console.error('下载过程中发生错误:', err); wx.showToast({title:'下载过程出现问题'}); } }) ``` 上述代码片段展示了完整的流程——从发起下载请求直到最终呈现给用户的整个链条,并且针对可能出现的各种情况都提供了相应的反馈措施[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值