408 lines
12 KiB
Vue
408 lines
12 KiB
Vue
<template>
|
|
<div class="component-upload-image">
|
|
<el-upload
|
|
ref="imageUploadRef"
|
|
multiple
|
|
:action="uploadImgUrl"
|
|
list-type="picture-card"
|
|
:on-success="handleUploadSuccess"
|
|
:before-upload="handleBeforeUpload"
|
|
:limit="limit"
|
|
:accept="fileAccept"
|
|
:on-error="handleUploadError"
|
|
:on-exceed="handleExceed"
|
|
:before-remove="handleDelete"
|
|
:show-file-list="true"
|
|
:headers="headers"
|
|
:file-list="fileList"
|
|
:on-preview="handlePictureCardPreview"
|
|
:class="{ hide: fileList.length >= limit }"
|
|
:http-request="customUpload"
|
|
>
|
|
<el-icon class="avatar-uploader-icon">
|
|
<plus />
|
|
</el-icon>
|
|
</el-upload>
|
|
<!-- 上传提示 -->
|
|
<div v-if="showTip" class="el-upload__tip">
|
|
请上传
|
|
<template v-if="fileSize">
|
|
大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
|
|
</template>
|
|
<template v-if="fileType">
|
|
格式为 <b style="color: #f56c6c">{{ fileType.join('/') }}</b>
|
|
</template>
|
|
的文件
|
|
</div>
|
|
|
|
<el-dialog v-model="dialogVisible" title="预览" width="800px" append-to-body>
|
|
<img :src="dialogImageUrl" style="display: block; max-width: 100%; margin: 0 auto" />
|
|
</el-dialog>
|
|
|
|
<!-- Bucket密码输入对话框 -->
|
|
<el-dialog v-model="passwordDialogVisible" title="Bucket访问密码" width="400px" append-to-body>
|
|
<el-form :model="passwordForm" label-width="100px">
|
|
<el-form-item label="Bucket密码" required>
|
|
<el-input
|
|
v-model="passwordForm.bucketPassword"
|
|
type="password"
|
|
placeholder="请输入bucket访问密码"
|
|
show-password
|
|
@keyup.enter="confirmPassword"
|
|
/>
|
|
</el-form-item>
|
|
</el-form>
|
|
<template #footer>
|
|
<span class="dialog-footer">
|
|
<el-button @click="passwordDialogVisible = false">取消</el-button>
|
|
<el-button type="primary" @click="confirmPassword">确认</el-button>
|
|
</span>
|
|
</template>
|
|
</el-dialog>
|
|
</div>
|
|
</template>
|
|
|
|
<script setup lang="ts">
|
|
import { ref, computed, watch, getCurrentInstance } from 'vue';
|
|
import { compressAccurately } from 'image-conversion';
|
|
import request from '@/utils/request';
|
|
|
|
// 定义props类型
|
|
interface Props {
|
|
modelValue?: string | any[] | any;
|
|
limit?: number;
|
|
fileSize?: number;
|
|
fileType?: string[];
|
|
isShowTip?: boolean;
|
|
compressSupport?: boolean;
|
|
compressTargetSize?: number;
|
|
bucketPassword?: string;
|
|
enablePasswordValidation?: boolean;
|
|
}
|
|
|
|
const props = withDefaults(defineProps<Props>(), {
|
|
modelValue: () => [],
|
|
limit: 15,
|
|
fileSize: 10,
|
|
fileType: () => ['png', 'jpg', 'jpeg'],
|
|
isShowTip: true,
|
|
compressSupport: false,
|
|
compressTargetSize: 300,
|
|
bucketPassword: '',
|
|
enablePasswordValidation: false
|
|
});
|
|
|
|
const { proxy } = getCurrentInstance() as any;
|
|
const emit = defineEmits(['update:modelValue']);
|
|
const number = ref(0);
|
|
const uploadList = ref<any[]>([]);
|
|
const dialogImageUrl = ref('');
|
|
const dialogVisible = ref(false);
|
|
|
|
// 密码相关
|
|
const passwordDialogVisible = ref(false);
|
|
const passwordForm = ref({
|
|
bucketPassword: ''
|
|
});
|
|
const pendingUploadFile = ref<any>(null);
|
|
|
|
// 上传的图片服务器地址(用于el-upload组件的action属性)
|
|
const uploadImgUrl = ref(import.meta.env.VITE_APP_BASE_API + '/resource/oss/upload');
|
|
|
|
// 设置正确的headers(用于el-upload组件)
|
|
const headers = ref({
|
|
'Authorization': 'Bearer ' + (localStorage.getItem('token') || ''),
|
|
'clientid': import.meta.env.VITE_APP_CLIENT_ID || 'e5cd7e4891bf95d1d19206ce24a7b32e',
|
|
'Content-Language': localStorage.getItem('language') || 'zh-CN',
|
|
'referer': window.location.origin + '/login?redirect=' + encodeURIComponent(window.location.pathname)
|
|
});
|
|
|
|
const fileList = ref<any[]>([]);
|
|
const showTip = computed(() => props.isShowTip && (props.fileType || props.fileSize));
|
|
|
|
const imageUploadRef = ref();
|
|
|
|
// 监听 fileType 变化,更新 fileAccept
|
|
const fileAccept = computed(() => props.fileType.map((type) => `.${type}`).join(','));
|
|
|
|
watch(
|
|
() => props.modelValue,
|
|
async (val: any) => {
|
|
if (val) {
|
|
// 首先将值转为数组
|
|
let list: any[] = [];
|
|
if (Array.isArray(val)) {
|
|
list = val;
|
|
} else if (typeof val === 'string') {
|
|
// 检查是否包含逗号分隔的URL
|
|
if (val.includes(',')) {
|
|
// 多个URL用逗号分隔
|
|
const urls = val.split(',').filter((url) => url.trim());
|
|
list = urls.map((url, index) => ({
|
|
ossId: url,
|
|
url: url.trim(),
|
|
originalName: `image_${index + 1}`
|
|
}));
|
|
} else if (val.startsWith('http://') || val.startsWith('https://')) {
|
|
// 单个URL
|
|
list = [{ ossId: val, url: val, originalName: 'image' }];
|
|
} else {
|
|
// 如果是OSS ID,暂时跳过接口调用
|
|
list = [{ ossId: val, url: val, originalName: 'image' }];
|
|
}
|
|
}
|
|
// 然后将数组转为对象数组
|
|
fileList.value = list.map((item, index) => {
|
|
// 字符串回显处理 如果此处存的是url可直接回显 如果存的是id需要调用接口查出来
|
|
let itemData;
|
|
if (typeof item === 'string') {
|
|
itemData = { name: item, url: item };
|
|
} else {
|
|
// 此处name使用url 防止删除出现重名,对于URL格式使用url_index的格式
|
|
const name = item.url && (item.url.startsWith('http://') || item.url.startsWith('https://')) ? `${item.url}_${index}` : item.ossId;
|
|
itemData = { name: name, url: item.url, ossId: item.ossId };
|
|
}
|
|
return itemData;
|
|
});
|
|
} else {
|
|
fileList.value = [];
|
|
return [];
|
|
}
|
|
},
|
|
{ deep: true, immediate: true }
|
|
);
|
|
|
|
/** 上传前loading加载 */
|
|
const handleBeforeUpload = (file: any) => {
|
|
let isImg = false;
|
|
if (props.fileType.length) {
|
|
let fileExtension = '';
|
|
if (file.name.lastIndexOf('.') > -1) {
|
|
fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1);
|
|
}
|
|
isImg = props.fileType.some((type: any) => {
|
|
if (file.type.indexOf(type) > -1) return true;
|
|
if (fileExtension && fileExtension.indexOf(type) > -1) return true;
|
|
return false;
|
|
});
|
|
} else {
|
|
isImg = file.type.indexOf('image') > -1;
|
|
}
|
|
if (!isImg) {
|
|
proxy?.$modal.msgError(`文件格式不正确, 请上传${props.fileType.join('/')}图片格式文件!`);
|
|
return false;
|
|
}
|
|
if (file.name.includes(',')) {
|
|
proxy?.$modal.msgError('文件名不正确,不能包含英文逗号!');
|
|
return false;
|
|
}
|
|
if (props.fileSize) {
|
|
const isLt = file.size / 1024 / 1024 < props.fileSize;
|
|
if (!isLt) {
|
|
proxy?.$modal.msgError(`上传头像图片大小不能超过 ${props.fileSize} MB!`);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
//压缩图片,开启压缩并且大于指定的压缩大小时才压缩
|
|
if (props.compressSupport && file.size / 1024 > props.compressTargetSize) {
|
|
proxy?.$modal.loading('正在上传图片,请稍候...');
|
|
number.value++;
|
|
return compressAccurately(file, props.compressTargetSize);
|
|
} else {
|
|
proxy?.$modal.loading('正在上传图片,请稍候...');
|
|
number.value++;
|
|
}
|
|
};
|
|
|
|
// 文件个数超出
|
|
const handleExceed = () => {
|
|
proxy?.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
|
|
};
|
|
|
|
// 自定义上传方法
|
|
const customUpload = async (options: any) => {
|
|
try {
|
|
// 检查是否需要bucket密码验证
|
|
if (props.enablePasswordValidation && !props.bucketPassword) {
|
|
// 显示密码输入对话框
|
|
pendingUploadFile.value = options;
|
|
passwordDialogVisible.value = true;
|
|
return;
|
|
}
|
|
|
|
// 添加小延迟,避免并发请求冲突
|
|
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
|
|
// 直接上传
|
|
await performUpload(options);
|
|
} catch (error) {
|
|
console.error('上传失败6:', error);
|
|
proxy?.$modal.msgError('上传失败7');
|
|
proxy?.$modal.closeLoading();
|
|
}
|
|
};
|
|
|
|
// 确认密码
|
|
const confirmPassword = async () => {
|
|
if (!passwordForm.value.bucketPassword) {
|
|
proxy?.$modal.msgError('请输入bucket访问密码');
|
|
return;
|
|
}
|
|
|
|
try {
|
|
// 密码验证成功,执行上传
|
|
if (pendingUploadFile.value) {
|
|
await performUpload(pendingUploadFile.value);
|
|
}
|
|
|
|
// 关闭对话框
|
|
passwordDialogVisible.value = false;
|
|
passwordForm.value.bucketPassword = '';
|
|
pendingUploadFile.value = null;
|
|
} catch (error) {
|
|
console.error('密码验证失败:', error);
|
|
proxy?.$modal.msgError('密码验证失败');
|
|
}
|
|
};
|
|
|
|
// 执行上传
|
|
const performUpload = async (options: any) => {
|
|
try {
|
|
const formData = new FormData();
|
|
formData.append('file', options.file);
|
|
|
|
// 添加bucket密码到FormData中
|
|
if (props.bucketPassword || passwordForm.value.bucketPassword) {
|
|
formData.append('bucket-password', props.bucketPassword || passwordForm.value.bucketPassword || '');
|
|
}
|
|
|
|
// 使用request方式调用接口,禁用防重复提交检查
|
|
const result = await request.post('/resource/oss/upload', formData, {
|
|
headers: {
|
|
'Content-Type': 'multipart/form-data',
|
|
'repeatSubmit': false // 禁用防重复提交检查
|
|
}
|
|
});
|
|
|
|
if (result.code === 200) {
|
|
// 上传成功
|
|
const uploadResult = {
|
|
name: result.data.fileName,
|
|
url: result.data.url,
|
|
ossId: result.data.ossId
|
|
};
|
|
|
|
uploadList.value.push(uploadResult);
|
|
uploadedSuccessfully();
|
|
} else {
|
|
throw new Error(result.msg || '上传失败1');
|
|
}
|
|
} catch (error: any) {
|
|
console.error('上传失败2:', error);
|
|
// 处理防重复提交错误
|
|
if (error.message && error.message.includes('数据正在处理,请勿重复提交')) {
|
|
proxy?.$modal.msgError('上传过于频繁,请稍后再试');
|
|
} else {
|
|
proxy?.$modal.msgError(error.message || '上传失败3');
|
|
}
|
|
proxy?.$modal.closeLoading();
|
|
}
|
|
};
|
|
|
|
// 上传成功回调
|
|
const handleUploadSuccess = (res: any, file: any) => {
|
|
// 确保res存在且有正确的结构
|
|
if (res && res.code === 200) {
|
|
// 避免重复添加,检查是否已经存在
|
|
const existingIndex = uploadList.value.findIndex((item) => item.name === res.data.fileName || item.ossId === res.data.ossId);
|
|
|
|
if (existingIndex === -1) {
|
|
uploadList.value.push({ name: res.data.fileName, url: res.data.url, ossId: res.data.ossId });
|
|
uploadedSuccessfully();
|
|
}
|
|
} else {
|
|
number.value--;
|
|
proxy?.$modal.closeLoading();
|
|
proxy?.$modal.msgError(res?.msg || '上传失败4');
|
|
if (file && imageUploadRef.value) {
|
|
imageUploadRef.value?.handleRemove(file);
|
|
}
|
|
uploadedSuccessfully();
|
|
}
|
|
};
|
|
|
|
// 删除图片
|
|
const handleDelete = (file: any): boolean => {
|
|
const findex = fileList.value.map((f) => f.name).indexOf(file.name);
|
|
if (findex > -1 && uploadList.value.length === number.value) {
|
|
const ossId = fileList.value[findex].ossId;
|
|
// 这里可以调用删除接口
|
|
fileList.value.splice(findex, 1);
|
|
emit('update:modelValue', listToString(fileList.value));
|
|
return false;
|
|
}
|
|
return true;
|
|
};
|
|
|
|
// 上传结束处理
|
|
const uploadedSuccessfully = () => {
|
|
if (number.value > 0 && uploadList.value.length === number.value) {
|
|
fileList.value = fileList.value.filter((f) => f.ossId !== undefined).concat(uploadList.value);
|
|
uploadList.value = [];
|
|
number.value = 0;
|
|
emit('update:modelValue', listToString(fileList.value));
|
|
proxy?.$modal.closeLoading();
|
|
}
|
|
};
|
|
|
|
// 上传失败5
|
|
const handleUploadError = () => {
|
|
proxy?.$modal.msgError('上传图片失败');
|
|
proxy?.$modal.closeLoading();
|
|
};
|
|
|
|
// 预览 - 使用安全预览
|
|
const handlePictureCardPreview = async (file: any) => {
|
|
try {
|
|
if (file.ossId) {
|
|
// 使用安全预览,这里简化处理
|
|
dialogImageUrl.value = file.url;
|
|
} else {
|
|
// 直接使用URL预览
|
|
dialogImageUrl.value = file.url;
|
|
}
|
|
dialogVisible.value = true;
|
|
} catch (error) {
|
|
console.error('预览失败:', error);
|
|
proxy?.$modal.msgError('预览失败');
|
|
}
|
|
};
|
|
|
|
// 对象转成指定字符串分隔
|
|
const listToString = (list: any[], separator?: string) => {
|
|
let strs = '';
|
|
separator = separator || ',';
|
|
for (const i in list) {
|
|
if (undefined !== list[i].ossId && list[i].ossId.indexOf('blob:') !== 0) {
|
|
// 返回ossId
|
|
strs += list[i].ossId + separator;
|
|
}
|
|
}
|
|
return strs != '' ? strs.substring(0, strs.length - 1) : '';
|
|
};
|
|
</script>
|
|
|
|
<style lang="scss" scoped>
|
|
// .el-upload--picture-card 控制加号部分
|
|
:deep(.hide .el-upload--picture-card) {
|
|
display: none;
|
|
}
|
|
|
|
.dialog-footer {
|
|
display: flex;
|
|
justify-content: flex-end;
|
|
gap: 10px;
|
|
}
|
|
</style>
|