Spring MVC处理文件上传

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.guavagroupId><artifactId>guavaartifactId><version>18.0version>
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中用户处理文件上传的输入框是

<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>

需要注意的是,务必指定

enctype属性为multipart/form-data才能支持将本地文件上传到服务器。


更多文章请访问 天码营网站



本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部