由于在小程序开发过程中多次用到图片上传功能,在最近一次项目开发时,决定将其打包成组件来提高复用性。
首先,在components文件夹下 新建Component,名称为 image-uploader
image-uploader.wxml
<view class="image-area">
<block wx:for="{{images}}" wx:key="index">
<view class="up-img">
<image class="uploader-img" src="{{item.url}}" mode="aspectFill"></image>
<view class="del" data-index="{{index}}" bindtap="delThisImg">
<image src="/images/del.png" class="del-image"></image>
</view>
</view>
</block>
<view class="upload-add" bindtap="uploadImage">
<image class="uploader-img" src="../../images/upadd.png" mode="aspectFill"></image>
</view>
</view>
image-uploader.js
let app = getApp()
Component({
/**
* 组件的属性列表
*/
properties: {
images: {
type: Array
}
},
/**
* 组件的初始数据
*/
data: {
},
/**
* 组件的方法列表
*/
methods: {
// 上传图片
uploadImage: function () {
let that = this
wx.chooseImage({
success(res) {
const tempFilePaths = res.tempFilePaths
tempFilePaths.forEach((element, index) => {
that.uploadFile('jpg,gif,png', element, 'image')
});
}
})
},
// 上传文件到服务器
uploadFile: function (uploadExt, path, type) {
let that = this
wx.uploadFile({
url: app.globalData.domain + 'base/upload/index?type=' + uploadExt,
filePath: path,
name: 'file',
formData: {},
success(res) {
let ret = JSON.parse(res.data)
// console.log(ret)
if (type == 'image') {
let images = that.data.images
images.push(ret.data)
that.setData({
images: images
})
that.triggerEvent('myevent',images)
}
}
})
},
// 删除上传的图片
delThisImg: function (e) {
let that = this
let images = that.data.images
images.splice(e.currentTarget.dataset.index, 1);
that.setData({
images: images
})
that.triggerEvent('myevent',images)
},
}
})
image-uploader.css
.image-area {
width: 100%;
}
.image-area:after{
content:"";
display: block;
visibility: hidden;
clear: both;
}
.up-img {
position: relative;
float: left;
margin-right: 8px;
}
.uploader-img {
width: 84px;
height: 84px;
}
.del {
position: absolute;
right: 0;
top: 0;
background-color: rgba(0, 0, 0, 0.8);
width: 20px;
height: 20px;
}
.del-image {
margin-top: 2px;
margin-left: 2px;
width: 16px;
height: 16px;
}
.upload-add {
float: left;
margin-bottom: 8px;
width: 84px;
height: 84px;
box-sizing: border-box;
background-color: #EDEDEd;
text-align: center;
vertical-align: middle;
}
引入组件相关代码:
// xml文件
<image-uploader images="{{images}}" onmyevent="getImages"></image-uploader>
// js文件
// 获取上传数据
getImages: function (e) {
this.setData({
images: e.detail
})
}