本篇文章,我们要来做一个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

Spring 文件上传功能的更多相关文章

  1. Spring +SpringMVC 实现文件上传功能。。。

    要实现Spring +SpringMVC  实现文件上传功能. 第一步:下载 第二步: 新建一个web项目导入Spring 和SpringMVC的jar包(在MyEclipse里有自动生成spring ...

  2. spring mvc 3.0 实现文件上传功能

    http://club.jledu.gov.cn/?uid-5282-action-viewspace-itemid-188672 —————————————————————————————————— ...

  3. springmvc中使用文件上传功能

    项目代码:https://github.com/PeiranZhang/springmvc-fileupload Servlet3.0之前使用文件上传功能 Servlet3.0之前需要使用common ...

  4. PHPCMS_V9 模型字段添加单文件上传功能

    后台有“多文件上传”功能,但是对于有些情况,我们只需要上传一个文件,而使用多文件上传功能上传一个文件,而调用时调用一个文件URL太麻烦了. 使用说明: 1.打开phpcms\modules\conte ...

  5. 配置php.ini实现PHP文件上传功能

    本文介绍了如何配置php.ini实现PHP文件上传功能.其中涉及到php.ini配置文件中的upload_tmp_dir.upload_max_filesize.post_max_size等选项,这些 ...

  6. MVC5:使用Ajax和HTML5实现文件上传功能

    引言 在实际编程中,经常遇到实现文件上传并显示上传进度的功能,基于此目的,本文就为大家介绍不使用flash 或任何上传文件的插件来实现带有进度显示的文件上传功能. 基本功能:实现带有进度条的文件上传功 ...

  7. Spring文件上传出错:java.lang.ClassCastException: org.apache.catalina.connector.Request

    java.lang.ClassCastException: org.apache.catalina.connector.RequestFacade cannot be cast to org.spri ...

  8. 用c++开发基于tcp协议的文件上传功能

    用c++开发基于tcp协议的文件上传功能 2005我正在一家游戏公司做程序员,当时一直在看<Windows网络编程> 这本书,把里面提到的每种IO模型都试了一次,强烈推荐学习网络编程的同学 ...

  9. Node.js新手教程——怎样实现文件上传功能

    作者:zhanhailiang 日期:2014-11-16 本文将介绍怎样使用Node.js实现文件上传功能. 1. 初始化项目信息:npm init [root@~/wade/nodejs/node ...

随机推荐

  1. UML:类图复习-鸡生蛋,蛋生鸡

    这是前一阵<高级软件工程>课堂上,老师随堂出的一道讨论题,随手贴在这里: ps: 今天是520,正好聊一些OoXx,关于爱的扯淡话题:) 题目:“鸡生蛋,蛋孵鸡”,世间万物生生不息,如何用 ...

  2. 基于ASP.NET MVC的热插拔模块式开发框架(OrchardNoCMS)--瘦身计划

    Orchard CMS是针对CMS开发的,对于很多开发需求来说,内容管理这块儿可能并不需要,而需要它的模块式开发模式.所以我这里通过对OrchardCMS进行瘦身,去除 内容管理部分的内容,保留简单的 ...

  3. Nginx 负载均衡

    Nginx简单实现网站的负载均衡 地址:http://www.cnblogs.com/alvin_xp/p/4161162.html

  4. Resharper快捷键

    建议你使用 Reshaper 的快捷键,不要担心 Reshaper 会把你原来的快捷键设置给覆盖了,因为如果某个快捷键和 VS 是冲突的,Reshaper会让你自己选择需要使用 VS 还是 Resha ...

  5. 样条函数 -- spline function

    一类分段(片)光滑.并且在各段交接处也有一定光滑性的函数.简称样条.样条一词来源于工程绘图人员为了将一些指定点连接成一条光顺曲线所使用的工具,即富有弹性的细木条或薄钢条.由这样的样条形成的曲线在连接点 ...

  6. Spring3+Mybatis3+Mysql+ivy+liquibase

    Spring3+Mybatis3+Mysql+ivy+liquibase 集成 近一周时间所学技术:整合Spring+MyBatis+MySql+ivy+liquibase Mybatis:是一个基于 ...

  7. Android几种打开SQLite的方法

    第一种:用SQLiteOpenHelper辅助类 SQLiteOpenHelper类可以用来创建或打开数据库,两个关键的方法:onCreate(SQLiteDatabase db)和onUpgrade ...

  8. 40-cut 简明笔记

    从输入行中选取字符或者字段 cut [options] [file-list] cut 从输入行中选取字符或者字段,并将他们写到标准输出,字符和字段从1开始编号 参数 file-list 是文件的路径 ...

  9. .NET中的垃圾回收

    目录 l         导言 l         关于垃圾回收 l         垃圾回收算法 m        应用程序根(Application Roots) l         实现 m   ...

  10. Android 用代码设置Shape,corners,Gradient

    网上查找资料 记录学习 int strokeWidth = 5; // 3dp 边框宽度 int roundRadius = 15; // 8dp 圆角半径 int strokeColor = Col ...