<template>
<el-dialog
v-model="dialogVisible3"
title="上传附件"
@close="handleClickClose"
width="25%"
>
<el-upload
ref="upload"
action="#"
drag
:auto-upload="false"
:on-change="onChange"
:before-remove="beforeRemove"
:file-list="fileList"
:before-upload="beforeUpload"
multiple
>
<el-icon class="el-icon--upload" style="width:30%"><upload-filled /></el-icon>
</el-upload>
<div class="button-container">
<el-button size="mini" type="success" @click="submit">提交</el-button>
<el-button type="primary" @click="handleClickClose">取消</el-button>
</div>
</el-dialog>
</template>
<script setup>
import { ref } from 'vue';
import { ElMessage, ElMessageBox,ElUpload } from 'element-plus';
const upload = ref();
const props=defineProps({
param:{
type: String,
default: -1,
},
goinitTable: Function //父组件的函数
})
const goinitTable = () => {
props.goinitTable()
}
const data = ref({
param1: '',
param2: ''
})
watch(
()=>props.param,
()=>{
if(props.param!= -1){
data.value.param1=props.param
}
}
)
const fileList = ref([]);
const ACCEPTED_EXTENSIONS = ['doc', 'xls', 'ppt', 'txt', 'pdf', 'png', 'jpg', 'jpeg'];
/**
* 请求前判断文件是否符合要求
* 如果符合则添加到上传队列
*/
function beforeUpload(file) {
const extension = file.name.split('.').pop().toLowerCase();
if (!ACCEPTED_EXTENSIONS.includes(extension)) {
ElMessage({
type: 'error',
message: '仅支持 doc, xls, ppt, txt, pdf, png, jpg 和 jpeg 格式的文件',
});
return false;
}
return true;
}
/**
* 文件选择改变时触发
*/
function onChange(file, fileListVal) {
fileList.value = fileListVal;
}
function beforeRemove(file, fileListVal) {
fileList.value = fileListVal;
}
/**
* 提交请求
* 处理上传逻辑
*/
async function submit() {
if (fileList.value.length === 0) {
return ElMessage.error('请选择要上传的文件');
}
const url = "后端上传Api";
const formData = new FormData();
fileList.value.forEach((file) => {
formData.append('file', file.raw);
});
formData.append('param1', data.value.param1);
formData.append('param2', data.value.param2);
try {
const response = await fetch(url, {
method: 'POST',
body: formData,
});
if (response.ok) {
const data = await response.json();
ElMessage({
type: 'success',
message: '文件上传成功',
});
clearAttachments();
handleClickClose()
emits("initTableList")
goinitTable()
} else {
throw new Error('文件上传失败');
}
} catch (error) {
ElMessage({
type: 'error',
message: error.message || '文件上传失败',
});
}
}
// 清空附件列表
const clearAttachments = () => {
if (upload.value) {
upload.value.clearFiles(); // 调用实例方法 `clearFiles` 清空附件列表
console.log("已清空附件列表");
}
};
/**向父组件抛出一个方法 */
const emits = defineEmits(['update:modelValue','initTableList']);
/**点击close触发 */
const handleClickClose = ()=>{
emits('update:modelValue',false);
}
</script>
<style scoped>
.button-container {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
}
::v-deep .el-upload {
width:100%;
}
</style>
Elementplus+vue3.x实现手动上传文件
于 2023-06-14 10:39:07 首次发布