微信小程序上传文件(可传 word、excel、ppt、视频、图片……)

文章目录

前言

近期做技术调研时发现微信官方支持文件上传了,这里记录一下
官方 API:wx.chooseMessageFile(Object object)

请添加图片描述

交互:从微信聊天里选择文件(选一个好友/群聊,从你们聊天记录里的文件里选)

  • 点红框是预览,点右上角圆圈才是选中(昨天做技术调研时点红圈部分是预览,搞得我还以为只支持图片选择)
    请添加图片描述

示例代码

wx.chooseMessageFile({
  count: 10,
  type: 'all',
  success (res) {
    // tempFilePath可以作为 img 标签的 src 属性显示图片
    // const tempFilePaths = res.tempFiles
    
    const tempFilePaths = res.tempFiles[0].path
    const type = res.tempFiles[0].type
    console.log(tempFilePaths, "tempFilePaths")
    console.log(type, "type")
    /*
    // word excel ppt
    wxfile://tmp_1a3a5917bca43c3fa77c11df43d416df10e46c19618252e4.docx tempFilePaths
    file type
    
    wxfile://tmp_9453f576fe6bfd2b18cfdc62cb91bda439fc0e8013eb6f7701d3e8395d132018.xlsx tempFilePaths
    file type
    
    wxfile://tmp_48974d797db4b2ea7ad8db76106385989b5941c6bfdc5b5b186608263fac11b9.pptx tempFilePaths
    file type
    
    // 视频、图片
    wxfile://tmp_21c1296f0b72c8d33cae70c993d5b85d95439b4940b4c07e.mp4 tempFilePaths
    video type
    
    wxfile://tmp_611597681c099cacb86e353b0b71adcb13a65700f46e8be7.jpg tempFilePaths
    image type
    */
  }
})

能拿到文件临时地址就能配合文件上传 API 将文件传上去了

  chooseUpload() {
    var that = this
    wx.chooseMessageFile({
      count: 10,
      type: 'file',
      extension: ['.xlsx', '.xls', '.XLSX', '.XLS', 'xlsx', 'xls', 'XLSX', 'XLS'],
      success(res) {
        const tempFilePaths = res.tempFiles
        for (var i in tempFilePaths) {
          wx.uploadFile({
            url: 'http://xxx', //上传的服务器地址
            filePath: tempFilePaths[i].path,
            name: 'file',
            formData: {
              'file': tempFilePaths[i].path
                   },

            header: {
              [wx.getStorageSync('tokenName')]: wx.getStorageSync('token'),
            },
            success: function (resp) {
              console.log(resp)
              var data = JSON.parse(resp.data)
              console.log(data)
              if (data.code == 200) {
                wx.showToast({
                  title: '上传成功',
                  icon: 'none',
                  duration: 1300
                })
              } else {
                wx.showToast({
                  title: data.message,
                  icon: 'none',
                  duration: 2000
                })
              }
            },
            fail: function (err) {
              console.log(err)
            }
          })
        }
      }
    })
  },

  • 5
    点赞
  • 61
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

RealizeInnerSelf丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值