微信小程序上传图片到服务器wx.uploadFile

项目中肯定会遇到上传文件到服务器端,小程序提供了很有用的api

wxml代码:

<image  mode='widthFix' src="{{imgUrl}}"></image>
<view bindtap="getPhoto">上传图片</view>

js代码:

getPhoto(e){   //获取手机相册功能
  let _this = this;
    wx.chooseImage({      
      count: 1,       //上传图片数量
      sizeType: ['original', 'compressed'],   
      sourceType: ['album', 'camera'],
      success(res) {
        console.log(res)
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths
      
        _this.upLoad(_this, tempFilePaths);   //调用上传接口
      }
    })

  },
  upLoad(that,filePath){
    wx.uploadFile({
      url: ROOT_URL,       //换成你自己的url地址
      filePath: filePath[0],    //图片文件 
      name: 'file',
      header: { 
        "Content-Type": "multipart/form-data",    //头部设置
      },
      formData: {
        //这里放你自己额外要带的参数
      },
      success: function (res) {
        //console.log(res)
        var data = JSON.parse(res.data) //do something 
       
          //根据你自己的项目要求,做处理
            this.setData({
                imgUrl:filePath[0]
            })

      }
    }) 
  },
  
  

猜你喜欢

转载自blog.csdn.net/qq_41806475/article/details/84539959