微信小程序 上传文件

2022-04-13  本文已影响0人  牛会骑自行车

很简单的头像上传的功能。因为小程序中不能new那个formData..着实费了点功夫。。。。。。

上代码 ↓
1.点击,选择图片,保存文件
https://developers.weixin.qq.com/miniprogram/dev/api/media/video/wx.chooseMedia.html

saveFile() {
      wx.chooseMedia({
        count: 1, // 可选文件数量。因为是头像上传,只一个文件就可
        mediaType: ["image"], // 文件类型:这里只是图片,其他使用看官网
        success: res => {
          this.uploadFile(res.tempFiles[0]); // 返回的数据里有我们后面上传需要的文件,保存下来
        },
        fail: err => {
          console.log(err, "personal.js >>>> 个人资料 上传头像")
        }
      })
},

2.将所需文件带去进行第二部调接口的操作。这两个也可以写到一起不过为了好看,我给它分开了
https://developers.weixin.qq.com/miniprogram/dev/api/network/upload/wx.uploadFile.html

  uploadFile(file) {
    wx.uploadFile({
      filePath: file.tempFilePath, // 上一步操作中带过来的文件
      name: 'imgurl', // 接口中要求的formData类型数据的参数
      url: `${getApp().globalData.baseUrl}applet/updateHeadPortrait`, // 接口
      formData: { // 其他数据类型的参数
        code: userInfo.code,
        type: userInfo.type
      },
      success: res => {
        console.log(res,'上传成功');
      },
      fail: err => {
        console.log(err, 'personal.js >>>> 个人资料')
      }
    })
  },

tada~~~微信小程序中的文件上传就完成啦~

上一篇 下一篇

猜你喜欢

热点阅读