微信小程序上传图片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

      }
    })
  },

猜你喜欢

转载自blog.csdn.net/a419419/article/details/79092988