微信小程序文件下载预览(wx.downloadFile) cv可用

730 阅读1分钟

使用两个微信小程序API:wx.downloadFilewx.openDocument

[wx.downloadFile用于下载文件资源到本地。客户端直接发起一个 HTTPS GET 请求,返回文件的本地临时路径 (本地路径),单次下载允许的最大文件为 200MB]

[wx.openDocument用于在新的页面中打开文档。它需要一个文件路径 (本地路径) ,可以通过 wx.downloadFile 获得。它还可以指定文件类型来打开文件]

当用户点击一个视图时,会触发 openPdf 函数。该函数首先调用api.Enterprise.getPolicyNum 方法,然后使用 wx.downloadFile 下载文档。下载成功后,它会使用 wx.openDocument 打开文档。如果打开文档失败,它会显示一个提示信息。

(注意 需要在微信开发配置 downloadFile合法域名 xxx.com 不然点击没效果)

 <block wx:for="{{restItems}}" wx:key="id">
      <view class="content" bindtap="openPdf" data-id="{{item.id}}" data-fileurl="{{item.fileurl}}">
        <view class="tip"></view>
        <view class="rig">
          <text>{{item.filename}}</text>
          <text>{{item.viewNum || 0}}</text>
        </view>
      </view>
    </block>
    
    async openPdf(e){
    let id = e.currentTarget.dataset.id
    let fileurl = 'https://xxx.com/' + e.currentTarget.dataset["fileurl"];
    wx.downloadFile({ //将文档下载到本地
      url: fileurl,//文件链接
      success(res) { 
        const filePath = res.tempFilePath
        wx.openDocument({ //打开文档
          filePath: filePath,//本地文档路径
          fileType: "docx",//文档类型
          showMenu: true,
          success: function (res) {
            // wx.showToast({
            //   title: '打开文档成功',
            // })
          },
          fail: function (res) {
            wx.showToast({
              title: '打开文档失败',
            })
          },
        })
      },
    })
  },