小程序预览文件、转发文件和选择微信文件
发布于 1 年前 作者 tluo 2531 次浏览 来自 分享

小程序针对文件的操作, 比如打开预览pdf, 转发文件给微信好友, 从微信好友选取文件

<button type="primary" bindtap="openFileClick">打开文件</button>

<button type="default" bindtap="shareFileClick">转发文件</button>

<button bindtap="chooseFileClick" type="primary">微信聊天文件选取</button>

<view wx:for="{{list}}" wx:key="index">
  <image wx:if="{{item.type=='image'}}" src="{{item.path}}"></image>
  <text wx:else>{{item.path}}</text>
</view>

// 开发者工具记得打开手机上的开发调试=>手机预览, 记得打开手机上的开发调试
Page({
  data: {
    // testUrl:'https://ppt.beegoedu.com/Upload/temp/20220523093604W6q.pdf' // 测试链接1
    testUrl:'http://storage.xuetangx.com/public_assets/xuetangx/PDF/PlayerAPI_v1.0.6.pdf' // 测试链接2
  },
  onLoad() {
 
  },
  // 打开文件
  openFileClick(){
    wx.downloadFile({
        url: this.data.testUrl,
        success:(res)=> {
          console.log(res)
          wx.openDocument({
            filePath: res.tempFilePath,
            success: (res)=> {
              console.log('打开文档成功')
            }
          })
        },
        fail:(err)=>{
          console.log(err)
        }
      })
  },
  // 转发文件
  shareFileClick(){
    wx.downloadFile({
      url: this.data.testUrl,
      success: function (res) {
        console.log(res)
        wx.shareFileMessage({
          filePath: res.tempFilePath,
          success() {
            console.log('转发文档成功')
          },
          fail: console.error,
        })
      },
      fail:(err)=>{
        console.log(err)
      }
    })
  },
   // 微信聊天选择文件
   chooseFileClick() {
    wx.chooseMessageFile({
      count: 10,
      type: "all", //all,video,image,file
      success:(res)=> {
        console.log(res);
        this.setData({
          list:res.tempFiles,
        });
      },
    });
  },
})

手机调试, 记得打开手机上的开发调试!!!

回到顶部