1、单文件
<form method="post" action="/upload" enctype="multipart/form-data">
<input type="file" name="file"><br>
<input type="submit" value="提交">
</form>
2、多文件
<form method="post" action="/upload" enctype="multipart/form-data">
<input type="file" name="files" multiple><br>
<input type="submit" value="提交">
</form>
3、controller
package com.springbootweb.Controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
@Controller
@Slf4j
public class UploadController {
/**
* MultipartFile 自动封装上传文件
*/
@PostMapping("/upload")
public String upload(@RequestParam String name,//基本属性
@RequestPart MultipartFile multipartFile,//单文件
@RequestPart MultipartFile[] multipartFiles//多文件
) throws IOException {
//获取基本信息
log.info("名称:"+name,"大小:"+multipartFile.getSize(),"数量:"+multipartFiles.length);
//保存到服务器
if(!multipartFile.isEmpty()){
//原始文件名
String fileName = multipartFile.getOriginalFilename();
//存放路径+保存后文件名
multipartFile.transferTo(new File("D:\\wenjian\\"+fileName));
}
if(multipartFiles.length>0){
for(MultipartFile file:multipartFiles){
if(!file.isEmpty()){
String tName = file.getOriginalFilename();
file.transferTo(new File("D:\\duowenjian\\"+tName));
}
}
}
//跳转首页
return "index";
}
}
4、配置
默认最大为1MB,可以修改配置为10MB
spring:
servlet:
multipart:
max-file-size: 10MB