天天看点

微信小程序上传图片wx.chooseImage和wx.uploadFile

微信小程序上传图片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: rpx;
  height: %;
  position: relative;
}
.photo-wrap{
  width: rpx;
  height: rpx;
  text-align: center;
  position: fixed;
  bottom: rpx;
}
.photo-image-wrap{
  width: rpx;
  height: rpx;
}
.photo-image-wrap image{
  width: rpx;
  height: rpx;
}
.photo-image-wrap text{
  font-size: px;
  color: #000000;
  letter-spacing: -px;
}
.photo-image-wrap1{
  position: absolute;
  left: rpx;
  bottom: rpx;
}
.photo-image-wrap2{
  position: absolute;
  right: rpx;
  bottom: rpx;
}
.close{
  width: rpx;
  height: rpx;
  position: absolute;
  left: %;
  margin-left: -rpx;
  bottom: rpx;
}
           

js:

getImage: function () {
    wx.chooseImage({
      count: , // 默认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[],
          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: , // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
      sourceType: ['camera'], // 可以指定来源是相册还是相机,默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths

      }
    })
  },