本篇文章,我们要来做一个Spring的文件上传功能:

1. 创建一个Maven的web工程,然后配置pom.xml文件,增加依赖:

      <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.0.2.RELEASE</version>
</dependency>

2.在webapp目录下的index.jsp文件中输入一个表单:

<html>
<body>
<form method="POST" enctype="multipart/form-data"
action="/upload">
File to upload: <input type="file" name="file"><br /> Name: <input
type="text" name="name"><br /> <br /> <input type="submit"
value="Upload"> Press here to upload the file!
</form>
</body>
</html>

这个表单就是我们模拟的上传页面。

3. 编写处理这个表单的Controller:

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream; import org.springframework.stereotype.Controller;
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.ResponseBody;
import org.springframework.web.multipart.MultipartFile; @Controller
public class FileUploadController { @RequestMapping(value="/upload", method=RequestMethod.GET)
public @ResponseBody String provideUploadInfo() {
return "You can upload a file by posting to this same URL.";
} @RequestMapping(value="/upload", method=RequestMethod.POST)
public @ResponseBody String handleFileUpload(@RequestParam("name") String name,
@RequestParam("file") MultipartFile file){
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(new File(name + "-uploaded")));
stream.write(bytes);
stream.close();
return "You successfully uploaded " + name + " into " + name + "-uploaded !";
} catch (Exception e) {
return "You failed to upload " + name + " => " + e.getMessage();
}
} else {
return "You failed to upload " + name + " because the file was empty.";
}
} }

4. 然后我们对上传的文件做一些限制,同时编写main方法来启动这个web :

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.embedded.MultiPartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; import javax.servlet.MultipartConfigElement; @Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application { @Bean
public MultipartConfigElement multipartConfigElement() {
MultiPartConfigFactory factory = new MultiPartConfigFactory();
factory.setMaxFileSize("128KB");
factory.setMaxRequestSize("128KB");
return factory.createMultipartConfig();
} public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

  5. 然后访问http://localhost:8080/upload就可以看到页面了。

上面的例子是实现的是单个文件上传的功能,假定我们现在要实现文件批量上传的功能的话,我们只需要简单的修改一下上面的代码就行,考虑到篇幅的问题,下面只是贴出和上面不同的代码,没有贴出的说明和上面一样。:

1.  新增batchUpload.jsp文件

<html>
<body>
<form method="POST" enctype="multipart/form-data"
action="/batch/upload">
File to upload: <input type="file" name="file"><br />
File to upload: <input type="file" name="file"><br />
<input type="submit" value="Upload"> Press here to upload the file!
</form>
</body>
</html>

2. 新增BatchFileUploadController.java文件:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List; /**
* Created by wenchao.ren on 2014/4/26.
*/ @Controller
public class BatchFileUploadController { @RequestMapping(value="/batch/upload", method= RequestMethod.POST)
public @ResponseBody
String handleFileUpload(HttpServletRequest request){
List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("file");
for (int i =0; i< files.size(); ++i) {
MultipartFile file = files.get(i);
String name = file.getName();
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(new File(name + i)));
stream.write(bytes);
stream.close();
} catch (Exception e) {
return "You failed to upload " + name + " => " + e.getMessage();
}
} else {
return "You failed to upload " + name + " because the file was empty.";
}
}
return "upload successful";
}
}

  这样一个简单的批量上传文件的功能就ok了,是不是很简单啊。

注意:上面的代码只是为了演示而已,所以编码风格上采取了随性的方式,不建议大家模仿。

参考资料:

1. MultipartResolver也可以实现文件上传功能。参考文章:http://mylfd.iteye.com/blog/1893648

最新文章

  1. 实现了一个百度首页的彩蛋——CSS3 Animation简介
  2. 在DBeaver中phoenix查询报错:org.apache.phoenix.exception.PhoenixIOException: The system cannot find the path specified
  3. 电信行业的BI应用
  4. 【POJ 3321】Apple Tree
  5. 安装jdk源码
  6. 数据库 MySql
  7. JBPM4.4+SSH 整合配置及完整实例
  8. UIControl事件
  9. MVC 项目 在前台使用DataTable
  10. 去除 waring Method &#39;CreateNew&#39; hides virtual method of base type &#39;TCustomForm&#39;
  11. Linux下vsftp服务器—上传、下载
  12. uva 11461
  13. c缺陷与陷阱笔记-第七章 可移植性代码
  14. 关于ListCtrol自绘的技巧
  15. freemarker入门实例
  16. 网易笔试题:浏览器中输入一个url后回车到返回页面信息的过程
  17. Linux基础指令
  18. Php如何返回json数据,前后端分离的基本解决方案
  19. 7. The British Thached Roof 英国的茅草屋顶
  20. Codeforces Round #417 (Div. 2) C. Sagheer and Nubian Market

热门文章

  1. Python2.7-异常和工具
  2. opencv6.4-imgproc图像处理模块之直方图与模板
  3. 让 HTML5 来为你定位
  4. PHP+mysql数据库开发搜索功能:中英文分词+全文检索(MySQL全文检索+中文分词(SCWS))
  5. Log4net使用(三)
  6. Codeforces Round #369(div 2)
  7. FileShare枚举的使用(文件读写锁)
  8. IOS自学
  9. Spring学习进阶(四) Spring JDBC
  10. iOS--更新cooped库