多文件上传,后端接收到多次请求
vue实现
<el-upload
class="upload-demo"
action="http://10.240.46.88:8081/upload1"
:on-preview="handlePreview"
:on-remove="handleRemove"
:multiple="multiple"
:limit="3"
:on-exceed="handleExceed"
:on-success="sucess"
:file-list="fileList">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
springboot后台@PostMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file) {
System.out.println("上传文件方法触发了");
//判断非空
if (file.isEmpty()) {
return "上传的文件不能为空";
}
try {
// 测试MultipartFile接口的各个方法
// logger.info("[文件类型ContentType] - [{}]",file.getContentType());
// logger.info("[文件组件名称Name] - [{}]",file.getName());
// logger.info("[文件原名称OriginalFileName] - [{}]",file.getOriginalFilename());
// logger.info("[文件大小] - [{}]",file.getSize());
// logger.info(this.getClass().getName()+"图片路径:"+path);
String path = "/Users/lijianxi/projects/javaproject/springlearn/src/main/resources/";
File f = new File(path);
// 如果不存在该路径就创建
if (!f.exists()) {
f.mkdir();
}
File dir = new File(path + file.getOriginalFilename());
// 文件写入
file.transferTo(dir);
return "上传单个文件成功";
} catch (Exception e) {
e.printStackTrace();
return "上传单个文件失败";
}
}
2.多文件上传,后端接收到一次请求
vue实现
<el-upload
class="upload-demo"
ref="upload"
action="http://10.240.46.88:8081/upload2"
:on-preview="handlePreview"
:on-remove="handleRemove"
:file-list="fileList"
:http-request="uploadFile"
:auto-upload="false">
<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
<el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
springboot后台
@PostMapping("/upload2")
public String upload2(@RequestParam("file")MultipartFile[] file){
System.out.println("-----22222--"+file.length);
String path = "/Users/lijianxi/projects/javaproject/springlearn/src/main/resources/";
if(file!=null&file.length>0) {
for (MultipartFile multipartFile : file) {
String fileName = multipartFile.getOriginalFilename();
File file1 = new File(path + fileName);
try {
multipartFile.transferTo(file1);
} catch (IOException e) {
e.printStackTrace();
return "上传失败";
}
System.out.println("");
}
}
System.out.println("上传成功");
return "多文件上传成功";
}
多文件上传时,默认的vue组件会将文件进行多次请求后端,为了可以实现一次请求,需要手动改造代码
html部分
修改:auto-upload="false"属性为false,阻止组件的自动上传
:http-request="uploadFile"覆盖上传事件
@click="submitUpload",给上传按钮绑定事件
js部分
在data中设置一个变量fileData
在方法中设置FormData的格式
通过ajax发送请求,携带参数为fileData
上传过程中报错:
TypeError: 'append' called on an object that does not implement interface FormData.
解决方法:
//报错请加入以下三行,则ajax提交无问题
cache: false,
processData: false,
contentType: false,
参考文章:http://blog.ncmem.com/wordpress/2023/12/11/springbootvue实现多文件上传/