本文为大家分享微信小程序的图片上传及图片预览功能,如下图所示:

需求分析:

  1. 图片上传可以从本地图库选择也可调用相机进行拍照上传
  2. 上传完成之后图片可以进行删除、预览等功能
  3. 图片上传至服务器进行后台调用

代码实现:

wxml文件

<view class="recovery_other_line">
 <view class="other_text">上传图片</view>
 <view wx:if="{{imageList.length}}" class="choose_upload_view">
   <view wx:for="{{imageList}}" wx:key="index" class="choose_upload_item">
   	 <!-- 图片上传展示 -->
     <image src="{{item}}" class="choose_upload_img" data-index="{{index}}" bindtap="previewBigImage"></image>
     <!-- 删除按钮 -->
     <image src="../../res/img/jdRecycleIcon/icon_remove.png" class="remove_img_icon" data-index="{{index}}" catchtap="removeChooseImage"></image>
   </view>
 </view>
 <!-- 上传按钮 -->
 <view class="other_right other_upload">
   <image src="../../res/img/jdRecycleIcon/icon_upload.png" class="upload_img" bindtap="chooseImageTap"></image>
 </view>
</view>

js文件

import { baseUrl} from './../../utils/request.js'

Page({
  data: {
  	imageList: [],      // 上传图片集合
  	form: {          // 用于其他功能提交的参数
  		ossUrl: []
  	}
  },
  // 选择上传图片的方式
  chooseImageTap() {
    let _this = this;
    wx.showActionSheet({
      itemList: ['从相册中选择', '拍一张'],
      itemColor: "#f7982a",
      success(res){
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            // 从相册中选择
            _this.chooseWxImage('album')
          } else if (res.tapIndex == 1) {
            // 使用相机
            _this.chooseWxImage('camera')
          }
        }
      }
    })
  },
  // 选择图片
  chooseWxImage(type) {
    let _this = this;
    let imgs = this.data.imageList;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: [type],
      success(res) {
        if (imgs.length > 2) {
          return wx.showToast({
            title: '最多可上传三张图片',
            icon: 'none'
          })
        }
        _this.upload(res.tempFilePaths[0]);
      }
    })
  },
  //上传图片到服务器
  upload: function(path) {
   let _this = this;
   let {ossUrl} = this.data.form;
   console.log(ossUrl)
    wx.showToast({
        icon: "loading",
        title: "正在上传"
      }),
      //将本地资源上传到服务器
      wx.uploadFile({
        url: baseUrl,    // 开发者服务器地址
        filePath: path,   // 要上传文件资源的路径 (本地路径)
        name: 'editormd-image-file',   // 文件对应的 key,开发者在服务端可以通过这个 key 获取文件的二进制内容
        header: {   
          // HTTP 请求 Header,Header 中不能设置 Referer
          "Content-Transfer-Encoding": "binary",
          "Content-Type": "application/octet-stream",
          "Content-Disposition": "form-data"
        },
        formData: {
          //和服务器约定的token, 一般也可以放在header中
          'token': wx.getStorageSync('userData').token,
        },
        success: function(res) {
          console.log(res)
          // 判断下
          if (res && res.data) {
            const data = JSON.parse(res.data);
            if (res.statusCode != 200) {
              wx.showToast({
                title: data.responseBody.data.message,
                icon: 'none'
              })
              return;
            } else {
              if (!!data.responseBody.data) {
                ossUrl.push(data.responseBody.data.url);
                _this.setData({
                  imageList: ossUrl,
                  'form.ossUrl': ossUrl  
                })
              }
            }
          }
        },
        fail: function(e) {
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          })
        },
        complete: function() {
          wx.hideToast(); //隐藏Toast
        }
      })
  },
  // 删除图片
  removeChooseImage(e) {
    let imgs = this.data.form.ossUrl;
    let {index} = e.currentTarget.dataset;
    imgs.splice(index, 1);
    this.setData({
      'form.ossUrl': imgs,
      imageList: imgs
    })
  },
  // 预览图片
  previewBigImage(e) {
    let imgs = this.data.imageList;
    let {index} = e.currentTarget.dataset;
    wx.previewImage({
      //当前显示图片
      current: imgs[index],
      //所有图片
      urls: imgs
    })
  }
})

css文件

.recovery_other_line {
  display: flex;
  line-height: 124rpx;
  align-items: center;
  justify-content: space-between;
}
.recovery_other_line .upload_img {
  width: 36rpx;
  height: 36rpx;
}
.recovery_other_line .other_text {
  width: 150rpx;
  font-size: 28rpx;
  color: #000;
}
.choose_upload_view {
  flex: 1;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
.choose_upload_item {
  margin-left: 38rpx;
  position: relative;
  width: 100rpx;
  display: flex;
  align-items: center;
}
.choose_upload_view .choose_upload_img {
  width: 100rpx;
  height: 100rpx;
}
.choose_upload_view .remove_img_icon {
  padding: 4rpx;
  position:absolute;
  top: -15rpx;
  right: -13rpx;
  width: 28rpx;
  height: 28rpx;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, .5);
}
.other_upload {
  margin-left: 15rpx;
  width: 80rpx;
}

以上就是本文的全部内容,希望对大家的学习有所帮助。。。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐