微信小程序上传组件(可同时长传图片+视频)

这篇博客展示了如何在微信小程序中创建一个上传组件,该组件同时支持图片和视频的上传,并能预览已上传的内容。通过`chooseMedia`接口选择多媒体文件,限制了文件大小不超过3MB,并提供了删除图片和视频的功能。上传的文件信息以特定格式抛出,方便进行多文件上传到服务器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

写了个微信小程序上传组件,同时支持上传视频+图片,并且可以返显。
废话不多说,上代码:

upload.wxml

<view class="clearfix">
  <view class="weui-uploader__file position" wx:for="{{imgs}}" wx:for-item="item" wx:key="*this">
    <image src="{{item.url}}" data-index="{{index}}" wx:if="{{item.type === 'image'}}" mode="aspectFill" bindtap="previewImg" class="list-img weui-uploader__img"></image>
    <video src="{{item.url}}" data-index="{{index}}" wx:if="{{item.type === 'video'}}" bindtap="previewImg" class="list-img weui-uploader__img"></video>
    <view class="delete-btn" data-index="{{index}}" catchtap="deleteImg">
      <icon type="clear" size="20" color="#fc5531"></icon>
    </view>
  </view>
  <view class="upload-img-btn weui-uploader__input-box" bindtap="chooseImg" ></view>
</view>

upload.js

Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgs: [],
  },

  chooseImg: function (e) {
    var that = this;
    var imgs = this.data.imgs;
    wx.chooseMedia({
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
      mediaType: ['mix'],
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFiles.forEach(item => {
          if (item.size > 3145728){
            wx.showToast({
              title: '文件不能超过3M',
              mask: true,
              duration: 1000
            })
            return ;
          }
          imgs.push({url:item.tempFilePath,type:item.fileType});
        });

        that.setData({
          imgs: imgs
        });
        console.log(that.data.imgs)
        that.triggerEvent('getUrl', {urls: imgs});
      }
    });
  },

  deleteImg(e){
    this.data.imgs.splice(e.currentTarget.dataset.index,1);
    this.setData({
      imgs: this.data.imgs
    })
  }
})

upload.wxss

/* components/upload/upload.wxss */
.clearfix::after {
  content: "";
  /* 内容为空 */
  visibility: hidden;
  /* 隐藏对象 */
  height: 0;
  display: block;
  clear: both;
}

.position{
  position: relative;
}

.img-chooseImage{
  width:200rpx;
  height: 200rpx;
  float: left;
  margin-right:20rpx;
  border-radius: 8rpx;
  position: relative;
}
.delete-btn{
  position: absolute;
  right:-14rpx;
  top:-20rpx;
  width: 40rpx;
  height: 40rpx;
}

.list-img{
  border:1px solid #ccc;
}
image{
  width:100%;
  height: 100%;
}

video{
  width:200rpx;
  height: 200rpx;
}

抛出的方法是getUrls,抛出的值格式为

{
	url:'',
	type:'' //值为image、video
}

处理传出值,利用微信小程序 多文件上传方法
一次性上传给服务器。
完~~~

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值