微信小程序上传图片

首先先实现点击添加图片和预览图片

在JS中创建 chooseImage实现点击添加图片

chooseImage: function (e) {
    var that = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
      success: function (res) {
        console.log(res);
        that.setData({
          imageList: res.tempFilePaths
        })
      }
    })
  }

创建p reviewImage实现预览图片

previewImage: function (e) {
    var current = e.target.dataset.src

    wx.previewImage({
      current: current,
      urls: this.data.imageList
    })
  }
上传图片需在后台写upload方法
public function upload($id=""){
      $upload = new \Think\Upload();//实例化上传类
      $upload->maxSize = 3145728;//设置附件上传大小
      $upload->exts = array('jpg','gif','png','jpeg');//设置附件上传类型
      $upload->rootPath = './Upload/';//设置附件上传根目录
      $upload->savePath = '';//设置附件上传子目录

      $info = $upload->uploadOne($_FILES['file']);

      if(!$info){
        return $this->ajaxReturn(array('error'=>true,'msg'=>$upload->getError()));
      }else{
        return $this->ajaxReturn(array('error'=>false,'msg'=>$info['savepath'].$info['savename'],'id'=>$id));
      }

    }
在小程序js中写
function upload(that,id){ if(that.data.imageList.length == 0){ return; } wx.uploadFile({ url:"", filePath: that.data.imageList[0], name:'file', formData:{ 'id':id }, success:function(res){ var data =res.data console.log(data); var json = JSON.parse(res.data); wx.showToast({ title:json.msg, icon:'none', duration:3000 })
}


formsubmit:function(e){
    wx.request({
      url:"",
      data:e.detail.value,
      method:'POST',
      header:{
        'content-type':'application/x-www-form-urlencoded'
      },
      success:(res)=>{
        console.log(res);
        if(res.error){
          wx.showToast({
            title: res.data.msg,
            icon:'none',
            duration:2000
          })
        }else{
          //上传图片
          // upload(this,res.data.id);

          wx.showToast({
            title: '添加成功!',
            icon:'success',
            duration:2000
          }),
          wx.navigateTo({
            url: '../camera/camera',
          })
        }
      }
    })
  }





你可能感兴趣的:(微信小程序上传图片)