小程序原生上传图片

wxml
<view class="imageList">
    <view class="imageItem" wx:for="{{imageList}}" wx:key="index">
        <image class="image"  mode="aspectFill" bindtap="chooseImage"  data-type="pictures"  data-index="{{index}}" src="{{item.url}}"  alt="" />
        <view class="delImage" catchtap="delImage" data-idnex="{{index}}">-</view>
    </view>
    <view class="imageItem addImage" bindtap="chooseImage"  data-type="pictures"></view>
</view>

js

Page({
  data: {
    imageList: []
  },
  //选择图片
  chooseImage(e) {
    let index=e.currentTarget.dataset.index
    console.log(index)
    let self = this
    wx.chooseMedia({
      count: 9,
      sizeType: ['original', 'compressed'], //原图 ,压缩图
      sourceType: ['album', 'camera'], //从相处选择 ,使用相机
      success(res) {
        console.log("res___________",res)
        res.tempFiles.forEach((file) => {
          if(index === undefined){ //添加图片
            self.setData({
              imageList: [...self.data.imageList, {
                url: file.tempFilePath
              }]
            })
          }else{ //替换当前索引下的图片
            self.data.imageList[index].url=file.tempFilePath
            self.setData({
              imageList:self.data.imageList
            })
          }
        })
      }
    })
  },
  //删除图片
  delImage(e) {
    let {
      imageList
    } = this.data
    let index = e.currentTarget.dataset.index
    imageList.splice(index, 1)
    this.setData({
      imageList
    })
  }
})

  css

.imageList {
  padding: 32rpx;
  width: 100vw;
  box-sizing: border-box;
 
  /* 弹性布局 */
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  /* 换行 */
  flex-wrap: wrap;
 
  /* 内容区的实际宽度为
   width: calc(100vw - 64rpx); 
   width: 686rpx; 
    */
 
}
 
/* 照片容器的样式 */
.imageList .imageItem {
  margin-bottom: 25rpx;
  width: 212rpx;
  height: 212rpx;
  background: #F7F9FD;
  border-radius: 8rpx;
  border: 5rpx dotted #D0D0D0;
  position: relative;
  /* overflow: hidden; */
  box-sizing: border-box;
}
 
.imageList .imageItem:nth-child(3n-1) {
  margin: 0 25rpx;
}
 
/* 图片的样式 */
.imageList .imageItem .image {
  display: block;
  width: 100%;
  height: 100%;
}
 
/* 删除按钮的样式 */
.imageList .imageItem .delImage {
  width: 32rpx;
  height: 32rpx;
  border-radius: 50%;
  background-color: #e40606;
   color: #ffffff;
  font-size: 32rpx;
  text-align: center;
  line-height: 22rpx;
  position: absolute;
  top: -16rpx;
  right: -16rpx;
 
  box-sizing: border-box;
}
 
/* 可以使用背景图 */
.imageList .addImage::before {
  display: block;
  content: "+";
  width: 100rpx;
  height: 100rpx;
  color: #cccccc;
  /* font-weight: 700; */
  font-size: 70rpx;
  text-align: center;
  line-height: 100rpx;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

  

posted @ 2023-05-09 17:38  MAKE-IN-LEMON  阅读(12)  评论(0编辑  收藏  举报