下面是图例
app中用到的图片上传很多,所以就将这个方法写成一个组件,下面是我的代码
1、在components中创建imgUpload.vue页面 (子组件)
<template>
<view class="l-fc l-fw" style="margin: 0 -6px;">
<block v-if="list&&list.length>0">
<view v-for="(item, index) in list" :key="index" class="c-bg-g2 o-mlr-s o-mt l-box" style="width: 140rpx;height: 140rpx;">
<view @click="deletePicture(index)" class="o-p-s" style="position: absolute;top:-26rpx;right: -20rpx;z-index: 90;">
<u-icon name="close-circle-fill" color="#dd524d" size="32"></u-icon>
</view>
<view class="wh100 c-of-h">
<image @click="$Function.PreviewImage(list,index)" class="w100" style="display: block;" mode="aspectFill" :src="item"></image>
</view>
</view>
</block>
<view @click="addPicture()" v-if="list.length<num" class="c-of-h c-bg-g1 o-mlr-s o-mt" style="width: 140rpx;height: 140rpx;">
<image class="wh100" src="../static/images/addImg.png"></image>
</view>
</view>
</template>
<script>
import config from '../common/config.js'; //用于图片上传地址的拼接
export default{
data() {
return{
list: [], //图片的列表
}
},
props:{
num: {
type: Number,
default: 9
},
idx: {
type: Number,
default: 0
},
imgs: {
type: Array,
default: function(){
return []
}
}
},
created() {
this.list = [...this.imgs]; //图片列表的合并
// console.log('this.imgs ==>', this.imgs)
},
methods:{
addPicture() {
uni.chooseImage({
count: this.num, // 最多可以选择的图片张数,默认9
sizeType: ['original', 'compressed'], // original 原图,compressed 压缩图,默认二者都有
sourceType: ['album', 'camera'], // album 从相册选图,camera 使用相机,默认二者都有
success: (chooseImageRes) => {
const tempFilePaths = chooseImageRes.tempFilePaths;
uni.showLoading({
title: '图片上传中...',
mask: true
});
var promise = Promise.all(tempFilePaths.map((pic, i) => {
return new Promise(async (resolve, reject) => {
let cimg = null;
// #ifdef APP-PLUS
cimg = await this.compress(pic),//上传图片之前先压缩,否则上传会比压缩先执行
// #endif
// #ifdef H5
cimg = pic,
// #endif
uni.uploadFile({
url: config.url_config+'endpoint/put-file-attach', //仅为示例,非真实的接口地址
header: {
"Blade-Auth": 'bearer ' + token
},
filePath: cimg,
name: 'file',
formData: {},
success: (uploadFileRes) => {
let data = JSON.parse(uploadFileRes.data)
resolve(data.data.link)
},
fail: (err) => {
console.log('err ==>', err)
}
});
})
}))
promise.then(res => {
// console.log('promise ==>', res)
this.list = this.list.concat(res)
this.$emit('upload', {list:this.list,idx:this.idx})
uni.hideLoading();
})
}
});
},
//删除图片
deletePicture(imgidx) {
let list = this.list; //图片的数组
uni.showModal({
title: '提示',
content: '确定要删除这张图片吗',
success:(res) => {
if (res.confirm) {
list.splice(imgidx, 1);
this.list = list;
setTimeout(() => {this.$emit('upload', {list:list,idx:this.idx})}, 200)
} else if (res.cancel) {
}
}
})
},
//压缩图片
compress(img){
// console.log('开始压缩 ==>',img);
return new Promise((resolve) => {
// var localPath = plus.io.convertAbsoluteFileSystem(img);
plus.io.resolveLocalFileSystemURL(img, (entry) => { //通过URL参数获取目录对象或文件对象
entry.file((file) => { // 可通过entry对象操作图片
// console.log('压缩前图片信息:' + JSON.stringify(file)); //压缩前图片信息
if(file.size > 512000) { // 如果大于500Kb进行压缩
plus.zip.compressImage({ // 5+ plus.zip.compressImage 了解一下,有详细的示例
src: img, //src: 压缩原始图片的路径
dst: img.replace('.png', '.png').replace('.PNG', '.PNG').replace('.jpg','.jpg').replace('.JPG','.JPG'),
width: '50%', //dst: (String 类型 )压缩转换目标图片的路径,这里先在后面原始名后面加一个2222区分一下
height: '50%', //width,height: (String 类型 )缩放图片的宽度,高度
quality: 70, //quality: (Number 类型 )压缩图片的质量
overwrite: true, //overwrite: (Boolean 类型 )覆盖生成新文件
// format:'jpg' //format: (String 类型 )压缩转换后的图片格式
},
(event) => {
// console.log('压缩后图片信息:' + JSON.stringify(event));// 压缩后图片信息
// this.imageInfo=event
let newImg = event.target;
resolve(newImg); //返回新的图片地址,在uploadFile之前接收
},
(err) => {
// console.log('Resolve file URL failed: ' + err.message);
});
}else{//else小于500kb跳过压缩,直接返回现有的src
resolve(img);
}
});
}, (e) => { // 返回错误信息
// console.log('Resolve file URL failed: ' + e.message);
});
})
}
}
}
</script>
<style>
</style>
2.引用这个组件
<template>
<img-upload v-if="true" :num='3' :idx="index" @upload="upload"></img-upload>
<img-upload v-else :imgs="Array.isArray(图片的数组)?info.repairImg:[]" :num="3" :idx="index" @upload="upload"></img-upload>
</template>
<script>
import imgUpload from '@/components/imgUpload.vue';
export default {
data() {},
components:{imgUpload},
methods: {
//获取子组件的图片
upload(e) {
// console.log('e ==>',e);
},
}
}
</script>