Spring MVC处理文件上传 由David发表在天码营
Spring MVC处理文件上传也是蜻蜓点水轻松惬意,今天让我们简单的学习一下吧。
环境准备
- 一个称手的文本编辑器(例如Vim、Emacs、Sublime Text)或者IDE(Eclipse、Idea Intellij)
- Java环境(JDK 1.7或以上版本)
- Maven 3.0+(Eclipse和Idea IntelliJ内置,如果使用IDE并且不使用命令行工具可以不安装)
初始化Spring MVC应用代码
参考Spring MVC快速入门建立一个最简单的基于Spring Boot的Web应用。在处理文件的过程中涉及到输入输出流的操作,为此引入Guava库依赖:
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
创建@Controller
处理文件上传请求
表单中添加的文件本质上也是表单中的一项,Spring使用MultipartFile
类对它进行了封装:
import com.google.common.io.Files;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
@RestController
public class FileUploadController {
@RequestMapping(value="/upload", method= RequestMethod.GET)
public String provideUploadInfo() {
return "You can upload a file by posting to this same URL.";
}
@RequestMapping(value="/upload", method=RequestMethod.POST)
public String handleFileUpload(@RequestParam("file") MultipartFile file) throws IOException {
if (!file.isEmpty()) {
String name = file.getOriginalFilename();
try {
Files.write(file.getBytes(), new File(name));
return "You successfully uploaded " + name + "!";
} catch (Exception e) {
return "You failed to upload " + name + " => " + e.getMessage();
}
} else {
return "You failed to upload because the file was empty.";
}
}
}
handleFileUpload()
方法获取上传的文件对象后,需要先判断其是否为空,如果不为空方才通过Files.write()
方法存储至文件系统。
文件上传配置
服务期程序处理用户上传的文件时,一个最重要的措施就是限制用户上传文件的大小,否则如果用户上传一个5GB大小的文件将会消耗巨大的服务器资源。使用Spring Boot框架,可以通过src/main/resources/application.properties
轻松配置这些参数:
multipart.maxFileSize=32MB
multipart.maxRequestSize=32MB
maxFileSize
限制的是总文件大小,maxRequestSize
限制的是包含multipart/form-data
表单数据的请求总大小,上述例子中都不能超过32MB,还可以使用KB, GB等单位进行配置。
文件上传表单
HTML中用户处理文件上传的输入框是<input type="file">
:
<html>
<body>
<form method="POST" enctype="multipart/form-data"
action="/upload">
File to upload: <input type="file" name="file"><br /> <br />
<input type="submit" value="Upload"> Press here to upload the file!
</form>
</body>
</html>
需要注意的是,务必指定<form>
的enctype
属性为multipart/form-data
才能支持将本地文件上传到服务器。