我的需求是,用户上传文件后,不自动上传到后台,需要另外点击上传按钮后再上传到后台
//EXCEL批量导入接口封装
export function uploadAPI(data) {
return request({
url: "/maintePollItem/uploadAPI",
method: "post",
data,
headers: {
"Content-Type": "multipart/form-data",//修改请求头为formData格式
},
});
}
<el-form :model="form" label-width="120px">
<el-form-item label="细项分类">
<el-select
v-model="form.type_id"
placeholder="请选择细项分类"
@change="(val) => selectChange(val, '上传细项分类')"
>
<el-option label="维护项" value="1" />
<el-option label="巡检项" value="2" />
</el-select>
</el-form-item>
<div style="display: flex; margin-top: 30px">
<el-upload
ref="upload"
class="upload-demo"
action=""
:limit="1"
:http-request="httpRequest"
:auto-upload="false"
:before-upload="beforeUpload"
:disabled="uploadDisabled"
>
<template #trigger>
<el-button type="primary">选择文件</el-button>
</template>
<template #tip v-if="uploadDisabled">
<div style="color: red">请先选择细项分类</div>
</template>
</el-upload>
</div>
</el-form>
<el-button type="primary" @click="confirmUpload">上传</el-button>
<el-button @click="cancelUpload">取消</el-button>
const isUpload = ref(false); //上传文件ref
const uploadDisabled = ref(true); //上传文件弹框禁用
//上传文件不自动走接口 点击按钮后上传
const confirmUpload = () => {
upload.value.submit();
};
//覆盖默认的 Xhr 行为,自行实现上传文件的请求
const httpRequest = (item) => {
let param = {
create_staff: userInfo.staffName,
type_id: form.type_id,
};
let formData = new FormData();
//获取上传文件
formData.append("file", item.file); //添加文件对象
formData.append("json", JSON.stringify(param)); //添加文件对象
const loading = ElLoading.service({
lock: true,
text: "加载中",
background: "rgba(0, 0, 0, 0.7)",
});
uploadAPI(formData)
.then((res) => {
loading.close();
if (res.Result_code == 200) {
ElMessage({
message: "导入细项成功",
type: "success",
});
} else if (res.Result_code == 400) {
ElMessage({
message: res.Result_msg,
type: "warning",
});
} else {
ElMessage({
message: "导入细项失败,请稍后再试",
type: "warning",
});
}
})
.catch(() => {
loading.close();
ElMessage({
message: "导入细项失败,请稍后再试",
type: "warning",
});
});
};
//上传文件之前的钩子 若返回false或者返回 Promise 且被 reject,则停止上传
const beforeUpload = (file) => {
const Xls = file.name.split(".");
if (Xls[1] !== "xls" && Xls[1] !== "xlsx") {
ElMessage({
message: "请上传excel格式的文件!",
type: "error",
});
return false;
}else if (file.size / 1024 / 1024 > 250) {
ElMessage({
message: "请上传250M以下的文件!",
type: "error",
});
return false;
}
return true;
};
//用户需要先选择类型 才能上传,否则 上传功能是禁用的
const selectChange = (value, label, toNull) => {
console.log(value, label);
if (label === "上传细项分类") {
uploadDisabled.value = false;
}
}
//取消上传 修改上传功能为禁用
const cancelUpload = () => {
uploadDisabled.value = true;
form.type_id = "";
};