微信小程序如何上传图片

技术概述

小程序对于上传图片的处理是小程序开发中基本都会用到的技术,特别是设置头像之类的地方,算是一个难点吧,也有很多文章介绍,包括微信小程序的官方文档。

技术详述

微信官方给出的上传图片功能是使用wx.chooseImage(Object object)完成的,参数如图

官方给出的代码示例如下

wx.chooseImage({
  count: 1,
  sizeType: ['original', 'compressed'],
  sourceType: ['album', 'camera'],
  success (res) {
    // tempFilePath可以作为img标签的src属性显示图片
    const tempFilePaths = res.tempFilePaths
  }
})

之后使用wx.uploadFile(Object object)把图片上传到服务器

官方示例代码:

wx.chooseImage({
  success (res) {
    const tempFilePaths = res.tempFilePaths
    wx.uploadFile({
      url: 'https://example.weixin.qq.com/upload', //仅为示例,非真实的接口地址
      filePath: tempFilePaths[0],
      name: 'file',
      formData: {
        'user': 'test'
      },
      success (res){
        const data = res.data
        //do something
      }
    })
  }
})

根据官方示例代码学着写就可以了

uploadImg() {
    let that = this;
    wx.chooseImage({
      count: 3 - that.data.uploaderNum,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
      success: function (res) {
        console.log(res)
        console.log(that.data.uploaderList)
        // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
        let tempFilePaths = res.tempFilePaths;
        let uploaderList = that.data.uploaderList.concat(tempFilePaths);
        if (uploaderList.length==3) {
          that.setData({
            showUpload: false
          })  
        }
        that.setData({
          uploaderList: uploaderList,
          uploaderNum: uploaderList.length,
          imgFileList: res.tempFiles
        })
      }
    })
  },

还有一些简单的操作,比如预览图片

previewImg: function (e) {
    var that = this;
    wx.previewImage({
      urls: that.data.uploaderList,
      current: that.data.uploaderList[e.currentTarget.dataset.index]
    })
  },

问题和解决过程

总结

微信小程序开发过程中,一定要和后端对接的同学之间保持交流,同时这也是我第一次接触小程序的编写,还有很多可以提高的地方,以后要加油咯。

参考文献、参考博客

微信官方文档·小程序·开发指南
微信小程序上传图片到服务器实例代码

posted @ 2021-06-28 14:52  Elsa1226  阅读(7347)  评论(0编辑  收藏  举报