<script setup>
|
import {computed, ref, reactive, defineEmits,watch} from "vue";
|
import {getToken} from "@/utils/auth.js";
|
import axios from "axios";
|
import {ElMessage} from "element-plus";
|
|
const emit = defineEmits(['update:fileList', 'onUpload',"update:ids"]);
|
|
const props = defineProps({
|
action: {type: String, default: "/common/minioUploads"},
|
fileList: {type: Array, default: () => []},
|
statusType: {type: Number, default: 0}
|
})
|
|
const localFileList = ref([...props.fileList])
|
|
|
const headers = computed(() => ({Authorization: "Bearer " + getToken()}));
|
const uploadFileUrl = computed(() => import.meta.env.VITE_APP_BASE_API + props.action);
|
|
const handleChange = () => {
|
emit('update:ids', localFileList.value.map(item => item.id))
|
emit('update:fileList', localFileList.value)
|
emit('onUpload', localFileList.value)
|
}
|
const handleUploadSuccess = (res, file) => {
|
// console.log(res)
|
localFileList.value.push(...res.data.map((it) => {
|
return {
|
id: it.id,
|
url: it.downloadUrl,
|
name: it.originalFilename,
|
status: "success",
|
uid: file.uid
|
}
|
}))
|
handleChange()
|
}
|
|
const handleUploadPreview = (it) => {
|
const link = document.createElement("a");
|
if (it.url) {
|
link.href = it.url
|
} else {
|
link.href = localFileList.value.find(fl => fl.uid === it.uid).url;
|
}
|
link.download = it.name;
|
link.click();
|
}
|
|
const handleUploadRemove = (it) => {
|
localFileList.value = localFileList.value.filter(f => f.uid !== it.uid);
|
handleChange()
|
}
|
|
watch(
|
() => props.fileList,
|
(val) => {
|
localFileList.value = [...val]
|
},
|
{ immediate: true, deep: true }
|
)
|
|
// 文件上传处理
|
const UploadImage = (param) => {
|
const formData = new FormData();
|
formData.append("files", param.file);
|
formData.append("type", props.statusType);
|
axios.post(uploadFileUrl.value, formData, {
|
headers: {
|
"Content-Type": "multipart/form-data",
|
...headers.value,
|
},
|
onUploadProgress: (progressEvent) => {
|
const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
|
param.onProgress({percent});
|
},
|
})
|
.then((response) => {
|
if (response.data.code === 200) {
|
handleUploadSuccess(response.data, param.file);
|
ElMessage.success("上传成功");
|
} else {
|
param.onError(new Error(response.data.msg));
|
ElMessage.error(response.data.msg);
|
}
|
})
|
.catch((error) => {
|
param.onError(error);
|
});
|
};
|
|
</script>
|
|
<template>
|
<div class="upload-file">
|
<el-upload
|
class="upload-demo"
|
drag
|
:fileList="localFileList"
|
:action="props.action"
|
:headers="headers"
|
:http-request="UploadImage"
|
:on-success="handleUploadSuccess"
|
:on-remove="handleUploadRemove"
|
:on-preview="handleUploadPreview"
|
multiple>
|
<i class="el-icon-upload"></i>
|
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
|
</el-upload>
|
</div>
|
</template>
|
|
<style scoped lang="scss">
|
|
|
|
</style>
|