springboot源码:
配置文件中添加:
server.port=8081
prop.upload-folder =C:/Users/LANGLANG/Desktop/123/
# Single file max size
multipart.maxFileSize=50Mb
# All files max size
multipart.maxRequestSize=50Mb
后端代码
@RestController
@CrossOrigin//跨域问题
public class UploadTest {
@Value("${prop.upload-folder}")
private String upload_folder;
@PostMapping("/singlefile")
public Object singleFileUpload(@RequestParam("files") MultipartFile[] files) {
System.out.println(files.length);
for (MultipartFile file : files) {
System.out.println(file.getName());
if(Objects.isNull(file) || file.isEmpty()) {
return "file is null,please upload again";
}
try {
byte[] bytes=file.getBytes();
Path path =Paths.get(upload_folder +file.getOriginalFilename());
//if hava not folder then create folder
if(!Files.isWritable(path)) {
Files.createDirectories(Paths.get(upload_folder));
}
Files.write(path,bytes);
}
catch(IOException e){
return "failure";
}
}
return "success";
}
}
前端Vue代码:
<template>
<div class="hello">
<h2>{{ msg }}</h2>
<form>
<input type="file" @change="getFile($event)" multiple="multiple" >
<button class="button button-primary button-pill button-small" @click="submit($event)">提交</button>
</form>
</div>
</template>
<script>
import axios from 'axios';
export default {
name: 'HelloWorld',
data() {
return {
msg: '多文件上传',
files:[]
}
},
methods: {
getFile: function (event) {
this.files = event.target.files;
alert(this.files.length);
console.log(this.files.length);
},
submit: function (event) {
//阻止元素发生默认的行为
event.preventDefault();
let formData = new FormData();
for (let i = 0; i < this.files.length; i++) {
formData.append("files", this.files[i]);
}
// var w=process.env.BASE_API;
// w=w+"/singlefile";
// console.log(w);
//axios.post('http://localhost:8081/singlefile', formData)
var w= 'http://localhost:8081/singlefile';
let config = {
headers: {
'Content-Type': 'multipart/form-data'
}
}
axios.post(w, formData,config)
.then(function (response) {
alert(response.data);
console.log(response);
window.location.reload();
})
.catch(function (error) {
alert("上传失败");
console.log(error);
window.location.reload();
});
}
}
}
</script>
需要注意的地方:
1、config :参数配置多文件类型;
2、前后端实现数据上传的主要关键是能够获取前端传回来的file类型数据。
其中两种方式:
@RequestParam("files") MultipartFile[] files。
同前端formData.append("files", this.files[i]);名称需要保持一致,否者无法获取数据,此处可以不使用RequestParam("files")
其他知识点:
1、设置上传上下限:
参考文章:https://www.cnblogs.com/s648667069/p/6510694.html
2、event.target.files[0]层层剖析
参考文章:https://blog.csdn.net/builder_fan/article/details/80271328
3、多个输入框填写
参考文章:https://blog.csdn.net/h363659487/article/details/79035388
4、更多关于formdata
参考文章:https://www.cnblogs.com/gr07/p/9628523.html
5、单个文件上传
参考文章:https://blog.csdn.net/oppo5630/article/details/79318715