2025-04-16 02:11:26 +01:00

158 lines
3.2 KiB
Vue
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<template>
<view class="">
<u-upload :fileList="isShowList?fileList:[]" @afterRead="afterRead" @delete="deletePic" :multiple="multiple"
:deletable="deletable" :maxCount="maxCount">
<slot></slot>
</u-upload>
<u-toast ref="uToast"></u-toast>
</view>
</template>
<script>
export default {
name: 'CustImageUpload', // 图片上传阅览
props: {
//单个文件上传大小M
maxSize: {
type: Number,
default: 1 //1M
},
//上传文件数量
maxCount: { // 限制数量
type: Number,
default: 1
},
//是否显示删除按钮
deletable: {
type: Boolean,
default: true
},
//是否多选
multiple: true,
//v-model的值
value: String,
//是否显示已上传图片列表
isShowList: {
type: Boolean,
default: false
}
},
data() {
return {
fileList: []
}
},
computed: {
/** 获取文件 url 前缀 */
baseUrl() {
return uni.$u.http.config.baseURL
}
},
watch: {
//拼接上url前面的部分
value(imgUrls) {
if (imgUrls) {
const {
baseUrl
} = this
this.fileList = imgUrls.split(',').map(url => ({
url: baseUrl + url,
status: 'success'
}))
}
}
},
methods: {
// 删除图片
deletePic(event) {
const {
fileList
} = this
const {
index
} = event
this.fileList = [
...fileList.slice(0, index),
...fileList.slice(index + 1)
]
this.emits()
},
// 新增图片
async afterRead(event) {
//多文件上传file是个数组集合
const files = Array.isArray(event.file) ? event.file : [event.file];
for (let file of files) {
console.log(file.size)
if (file.size > this.maxSize * 1024 * 1224) {
console.log('走判断了');
this.$refs.uToast.show({
type: 'error',
icon: false,
title: '图片超过大小',
message: "图片大小不超过" + this.maxSize + 'M',
});
continue;
}
const updatedFile = {
...file,
status: 'uploading',
message: '上传中'
};
this.fileList.push(updatedFile);
const {
url
} = await this.uploadFile(file.thumb);
updatedFile.status = 'success';
updatedFile.message = '上传完成';
updatedFile.url = url;
}
this.emits();
},
//文件上传接口
uploadFile(url) {
//这是用promise封装异步请求
return new Promise((resolve, reject) => {
uni.$u.http.upload('/common/upload', {
filePath: url,
name: 'file',
timeout: 60000 //超时时间设置为1分钟防止时间过短无法上传
}).then(res => {
resolve(res);
}).catch(error => {
reject(error)
});
});
},
/** 抛出事件 */
emits() {
const {
fileList
} = this;
//截取掉url前面的部分
const imgUrls = fileList.map(({
url
}) => {
//找到/profile/upload出现的位置位置就是/的索引
const i = url.indexOf('/profile/upload')
//截取索引后面的部分
return url.slice(i)
//最后将数组元素按照,拼接成字符串
}).join(',')
this.$emit('input', imgUrls)
}
}
}
</script>
<style>
</style>