Spring Boot上传文件只需要在controller的方法上设置一个MultipartFile 参数即可,当然可以用@RequestParam指定方法名,如果是上传多个file时,可以使用数组,另外也可以用一个成员变量为MultipartFile的类来接收文件和其他参数。
为了演示它,我们需要有页面来上传文件,引入thymeleaf模板引擎。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
在resources/templates下增加一个html文件:
<html xmlns:th="http://www.thymeleaf.org">
<body>
<div th:if="${message}">
<h2 th:text="${message}"/>
</div>
<div>
<form method="POST" enctype="multipart/form-data" action="/upload/uploadfile">
<table>
<tr><td>File to upload:</td><td><input type="file" name="file" /></td></tr>
<tr><td></td><td><input type="submit" value="Upload" /></td></tr>
</table>
</form>
</div>
</body>
</html>
写一个Controller类,一个用来Get页面,一个用来打印提交的file内容。
@Controller
@RequestMapping("upload")
public class UploadFileController {
@GetMapping("/file")
public String file(Model model){
model.addAttribute("message", "测试");
return "file";
}
@PostMapping("/uploadfile")
@ResponseBody
public Object uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
File file1 = new File("/tmp/abc.log");
file.transferTo(file1);
FileInputStream in = null;
InputStreamReader inReader = null;
BufferedReader bufReader = null;
try {
in = new FileInputStream(file1);
inReader = new InputStreamReader(in, "UTF-8");
bufReader = new BufferedReader(inReader);
String line = null;
int i = 1;
while ((line = bufReader.readLine()) != null) {
System.out.println("第" + i + "行:" + line);
i++;
}
}catch (Exception e){
e.printStackTrace();
}finally {
if(bufReader != null) {
bufReader.close();
}
if(inReader != null) {
inReader.close();
}
if(in != null) {
in.close();
}
}
return "OK";
}
}
运行之后,上传个文件,控制台打印如下:
第1行:aaa
第2行:bbb
第3行:Ccc