1、pom.xml依赖
<dependencies>
<!-- spring boot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
</dependency>
</dependencies>
2、接口
2.1 一般参数
private Logger logger = LoggerFactory.getLogger(getClass());
private String filePath = "D:/1/";
@RequestMapping("/upLoadFile")
public User uploadFiles(@RequestParam("file") MultipartFile[] files,@RequestParam("em") String em) throws IOException {
logger.info("em:{}",em);
for (int i = 0; i < files.length; i++) {
try {
uploadFile(files[i].getBytes(), files[i].getOriginalFilename());
} catch (Exception e) {
e.printStackTrace();
logger.info("上传文件发生错误");
}
}
return new User("1", "张三", 12);
}
private void uploadFile(byte[] file, String fileName) throws Exception {
File targetFile = new File(filePath);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
FileOutputStream out = new FileOutputStream(filePath + fileName);
out.write(file);
out.flush();
out.close();
}
2.2 对象注入
2.2.1 对象类型
import org.springframework.web.multipart.MultipartFile;
/**
* @Title: FormData.java
* @Package com.spring.pro.model
* @Description:
* @author ybwei
* @date 2018年11月14日 下午4:37:15
* @version V1.0
*/
public class FormData {
private String name;
private String email;
private MultipartFile file;
private MultipartFile file2;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public MultipartFile getFile() {
return file;
}
public void setFile(MultipartFile file) {
this.file = file;
}
public MultipartFile getFile2() {
return file2;
}
public void setFile2(MultipartFile file2) {
this.file2 = file2;
}
}
2.2.2 接口
@RequestMapping("/upLoadFile2")
public User uploadFiles2(@ModelAttribute FormData fd) throws Exception {
logger.info("fd:{}",JSON.toJSONString(fd));
uploadFile(fd.getFile().getBytes(), fd.getFile().getOriginalFilename());
uploadFile(fd.getFile2().getBytes(), fd.getFile2().getOriginalFilename());
return new User("1", "张三", 12);
}
2.2.3 @ModelAttribute
- 应用到方法
- 应用到方法参数
- 应用到方法上,方法使用了@RequestMapping
2.2.2 使用的是2。绑定请求参数到命令对象:放在功能处理方法的入参上时,用于将多个请求参数绑定到一个命令对象,从而简化绑定流程,而且自动暴露为模型数据用于视图页面展示时使用。
3、测试
参考https://blog.csdn.net/xixingzhe2/article/details/82982453