写了个微信小程序上传组件,同时支持上传视频+图片,并且可以返显。
废话不多说,上代码:
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
}
处理传出值,利用微信小程序 多文件上传方法
一次性上传给服务器。
完~~~