前端使用Vue,后端使用SpirngBoot,实现通过网页上传单个文件或者多个文件到后端服务器
一.单个文件上传
html部分
<input class="file" name="file" type="file" @change="update"/>
js部分
update(e){
let file = e.target.files[0];
let param = new FormData(); //创建form对象
param.append('file',file);//通过append向form对象添加数据
let config = {
headers:{'Content-Type':'multipart/form-data'}
}; //添加请求头
this.$axios.post('/controller/uploadFile/single',param,config)
.then(response=>{
console.log(response.data);
})
}
java后端部分
@PostMapping("/controller/uploadFile/single")
public String uploadFileSingle(@RequestParam("file") MultipartFile file) {
if(file!=null){
System.out.println(file.length);
return "ok";
}else{
return "fail";
}
}
二.多个文件上传
html部分
<input class="file" multiple name="file" type="file" @change="update"/>
js部分
update(e){
let files = e.target.files;
let param = new FormData(); //创建form对象
for(let i=0;i<files.length;i++){
param.append('file',files[i]);//通过append向form对象添加数据
}
let config = {
headers:{'Content-Type':'multipart/form-data'}
}; //添加请求头
this.$axios.post('/controller/uploadFile/batch',param,config)
.then(response=>{
console.log(response.data);
})
}
java部分
@PostMapping("/controller/uploadFile/batch")
public String uploadFileBatch(@RequestParam("file") MultipartFile[] files) {
if(files!=null){
System.out.println(files.length);
return "ok";
}else{
return "fail";
}
}