1. 程式人生 > >微信小程式上傳圖片到伺服器wx.uploadFile

微信小程式上傳圖片到伺服器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]
            })

      }
    }) 
  },