
组件代码,直接在需要的地方引入即可,只需更改data中的地址为自己的服务器地址
<template>
<view>
<view class="qtpicker">
<view class="preImgs" v-for="(val,index) in preImgUrl" :key='index'>
<image mode="" :src="val" @click="showImg(val,index)">
</image>
<view class="cuo" @click="delImg(index)">×</view>
</view>
<view class="addImg" @click="chooseImg">
<view>+</view>
<view>添加图片</view>
</view>
</view>
<button type="primary" @click="submitImg">确定上传</button>
</view>
</template>
<script>
export default {
data() {
return {
preImgUrl: [],
imgNum: 0,
serverUrl: 'http://www.baidu.com',
}
},
methods: {
chooseImg() {
let that = this
uni.chooseImage({
count: 2,
sizeType: "original,compressed",
success: function(res) {
console.log(res, '选择成功')
res.tempFiles.map(val => {
if (val.size > 10485760) {
uni.showToast({
icon: 'none',
title: '上传的图片大小不超过10M'
})
return
}
that.imgNum++
if (that.imgNum > 9) {
that.imgNum = 9
uni.showToast({
icon: 'none',
title: '上传的图片最多不能超过9张'
})
return
}
that.preImgUrl.push(val.path)
})
}
})
},
showImg(val, index) {
console.log(val, '点击了')
let that = this
uni.previewImage({
urls: that.preImgUrl,
current: index,
})
},
delImg(index) {
this.preImgUrl.splice(index, 1)
},
submitImg() {
let that = this
if (that.preImgUrl.length == 0) {
uni.showToast({
icon: 'none',
title: '请先选择图片'
})
return
}
that.preImgUrl.map(val => {
uni.uploadFile({
url: that.serverUrl,
filePath: val,
name: 'image',
header: {
"Content-Type": "multipart/form-data"
},
success(res) {
console.log(res, '上传成功')
uni.showToast({
icon: 'none',
title: '上传成功'
})
},
fail(res) {
console.log(res, '上传失败')
uni.showToast({
icon: 'none',
title: '上传失败'
})
}
})
})
}
}
}
</script>
<style scoped lang="scss">
* {
box-sizing: border-box;
}
.qtpicker {
width: 100%;
display: flex;
flex-direction: row;
flex-wrap: wrap;
margin: 0 auto;
padding: 10rpx 0;
.preImgs {
margin: 13rpx;
position: relative;
image {
width: 125rpx;
height: 125rpx;
}
.cuo {
width: 35rpx;
height: 35rpx;
line-height: 30rpx;
text-align: center;
font-size: 30rpx;
border-radius: 50%;
background-color: #ff0000;
color: #FFFFFF;
position: absolute;
right: -17.5rpx;
top: -17.5rpx;
}
}
.addImg {
width: 125rpx;
height: 125rpx;
border: 2rpx solid #d4d4d4;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: 20rpx;
// background-color: #ebebeb;
margin: 13rpx;
}
}
</style>
父引入
<template>
<view class="box">
<picker-img></picker-img>
</view>
</template>
<script>
import pickerImg from './components/pickerImg/pickerImg.vue'
export default {
components: {pickerImg},
}
</script>
<style scoped lang="scss">
</style>