1. 程式人生 > 程式設計 >微信小程式實現上傳圖片的功能

微信小程式實現上傳圖片的功能

本文例項為大家分享了微信小程式實現上傳圖片的具體程式碼,供大家參考,具體內容如下

效果圖

微信小程式實現上傳圖片的功能微信小程式實現上傳圖片的功能微信小程式實現上傳圖片的功能

WXML

<view class="img-wrap">
  <view class="txt">上傳圖片</view>
  <view class="imglist">
    <view class="item" wx:for="{{imgs}}" wx:key="item">
      <image src="{{item}}" alt="微信小程式實現上傳圖片的功能"></image>
      <view class='delete' bindtap='deleteImg' data-index="{{index}}">
        <image src="../../../images/icon.png"></image>
      </view>
    </view>
    <view class="last-item" wx:if="{{imgs.length >= 3 ? false : true}}" bindtap="bindUpload">
      <text class="sign">+</text>
    </view>
  </view>
</view>


data: {
  imgs: [],count: 3
},bindUpload: function (e) {
  switch (this.data.imgs.length) {
    case 0:
      this.data.count = 3
      break
    case 1:
      this.data.count = 2
      break
    case 2:
      this.data.count = 1
      break
  }
  var that = this
  wx.chooseImage({
    count: that.data.count,// 預設3
http://www.cppcns.com
sizeType: ["original","compressed"],// 可以指定是原圖還是壓縮圖,預設二者都有 sourceType: ["album","camera"],// 可以指定來源是相簿還是相機,預設二者都有 success: function (res) { // 返回選定照片的本地檔案路徑列表,tempFilePath可以作為img標籤的src屬性顯示圖片 var tempFilePaths = res.tempFilePaths for (var i = 0; i < tempFilePaths.length; i++) { wx.uploadFile({ url: 'https://graph.baidu.com/upload',filePath: tempFilePaths[i],name: "file",header: { "content-type": "multipart/form-data" },success: function (res) { if (res.statusCode == 200) { wx.showToast({ title: "上傳成功",icon: "none",duration: 1500 }) that.data.imgs.push(JSON.parse(res.data).data) http://www.cppcns.com
that.setData({ imgs: that.data.imgs }) } },fail: function (err) { wx.showToast({ title: "上傳失敗",duration: 2000 }) },complete: function (result) { console.log(result.errMsg) } }) } } }) },// 刪除圖片 deleteImg: function (e) { var that = this wx.showModal({ title: "提示",content: "是否刪除",success: function (res) { if (res.confirm) { for (var i = 0; i < that.data.imgs.length; i++) { if (i == e.currentTarget.dataset.index) that.data.imgs.splice(i,1) } that.setData({ imgs: that.data.imgs }) } else if (res.cancel) { console.log("使用者點選取消") } } }) }


WXSS

.wrap {
  width: 100%;
  padding: 0 30rpx;
  box-sizing: border-box;
}
.wrap .img-wrap {
  font-size: 30rpx;
  color: #33373E;
  margin-bottom: 10rpx;
}
.wrap .img-wrap .txt {
  margin-bottom: 20rpx;
}
.wrap .img-wrap .imglist {
  display: flex;
  flex-wrap: wrap;
}
.wrap .img-wrap .imglist .item {
  width: 150rpx;
  height: 150rpx;
  margin-right: 22rpx;
  margin-bottom: 10rpx;
  position: relative;
}
.wrap .img-wrap .imglist .last-item {
  width: 150rpx;
  height: 150rpx;
  text-align: center;
  line-height: 146rpx;
  border: 2rpx dwww.cppcns.comashed #8B97A9;
  box-sizing: border-box;
}
.wrap .img-wrap .imglist .item image {
  width: 100%;
  hewww.cppcns.comight: 100%;
}
.wrap .img-wrap .imglist .item .delete {
  width: 30rpx;
  height: 30rpx;
  position: absolute;
  top: -14rpx;
  right: -12rpx;
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。