1. 程式人生 > >微信小程式上傳圖片wx.chooseImage和wx.uploadFile

微信小程式上傳圖片wx.chooseImage和wx.uploadFile

這裡寫圖片描述
這裡寫圖片描述
wxml:

<view class="container">
  <view class='photo-wrap'>
    <view class='photo-image-wrap photo-image-wrap1'>
      <image src='/images/photo2.png' bindtap='getImage'></image>
      <text>相簿</text>
    </view>
    <view class='photo-image-wrap photo-image-wrap2'
>
<image src='/images/photo1.png' bindtap='takePhoto'></image> <text>拍攝</text> </view> <navigator url='/pages/index/index'> <image src='/images/close1.png' class='close'></image> </navigator> </view> </view>

wxss:

/**index.wxss**/
.container{
  width: 750rpx;
  height: 100%;
  position: relative;
}
.photo-wrap{
  width: 750rpx;
  height: 420rpx;
  text-align: center;
  position: fixed;
  bottom: 0rpx;
}
.photo-image-wrap{
  width: 196rpx;
  height: 260rpx;
}
.photo-image-wrap image{
  width: 190rpx;
  height: 190rpx
; }
.photo-image-wrap text{ font-size: 17px; color: #000000; letter-spacing: -0.41px; } .photo-image-wrap1{ position: absolute; left: 120rpx; bottom: 220rpx; } .photo-image-wrap2{ position: absolute; right: 120rpx; bottom: 220rpx; } .close{ width: 56rpx; height: 56rpx; position: absolute; left: 50%; margin-left: -28rpx; bottom: 20rpx; }

js:

  getImage: function () {
    wx.chooseImage({
      count: 1, // 預設9
      sizeType: ['original', 'compressed'], // 可以指定是原圖還是壓縮圖,預設二者都有
      sourceType: ['album'], // 可以指定來源是相簿還是相機,預設二者都有
      success: function (res) {
        // 返回選定照片的本地檔案路徑列表,tempFilePath可以作為img標籤的src屬性顯示圖片
        var tempFilePaths = res.tempFilePaths
        wx.uploadFile({
          url: app.globalData.URL +'/uploadMaterial',
          filePath: res.tempFilePaths[0],
          name: 'file',
          formData: {
            'token': app.globalData.token,//一個簽名認證,本專案的需要,其他專案不一定要
          },
          header: { "Content-Type": "multipart/form-data" },
          success: function (result) {
            var resultData = JSON.parse(result.data)
            console.log(resultData.data.url);
          },
          fail: function (e) {
            console.log(e);
          }
        })
      }
    })
  },
    takePhoto: function () {
    wx.chooseImage({
      count: 1, // 預設9
      sizeType: ['original', 'compressed'], // 可以指定是原圖還是壓縮圖,預設二者都有
      sourceType: ['camera'], // 可以指定來源是相簿還是相機,預設二者都有
      success: function (res) {
        // 返回選定照片的本地檔案路徑列表,tempFilePath可以作為img標籤的src屬性顯示圖片
        var tempFilePaths = res.tempFilePaths

      }
    })
  },