vue3+elementplus 单文件上传
端前
<template>
<el-upload
multiple
action="#"
class="upload-demo"
:auto-upload="false"
:on-change="change">
<el-button type="primary">上传</el-button>
</el-upload>
<template>
const change = (data) => {
let formData = new FormData();
formData.append('file', data.raw);
// 检查是否成功添加数据到 FormData 对象中
if (formData.has('file')) {
console.log('FormData 中包含数据');
console.log(formData.get('file')); // 检查 'file' 字段是否被正确添加到 FormData 中
} else {
console.log('FormData 中没有数据');
}
ipmExcel(formData).then(response => {
console.log("222222",response);
})
}
js接口
export function ipmExcel(data) {
return request({
url: '/wxhxpfqczfx/fqcz/importData',
method: 'post',
data: data
})
}
后端
@PostMapping("/importData")
public AjaxResult importData(MultipartFile file) throws Exception {
if (file == null) {
throw new ServiceException("文件上传失败,文件对象为空!");
}
if (file.isEmpty() ||file == null) {
throw new ServiceException("文件上传失败!");
}
// 获取文件名
String originalFilename = file.getOriginalFilename();
// 获取文件后缀名
String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
// 设置文件上传绝对路径
String filePath = "F:\\anDongQing\\static\\images\\";
// 重新定义文件名称
String fileName = suffixName;
// 获取上传文件的File对象
File dest = new File(filePath + fileName);
System.out.println(dest);
// 开始上传
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
String message = "操作成功";
return AjaxResult.success(message); //new AjaxResult("操作成功"); // 返回操作成功的结果
} catch (Exception e) {
e.printStackTrace();
String message = "上传失败";
return AjaxResult.success(message); //new AjaxResult(false, "上传失败"); // 返回操作失败的结果
}
}