Spring 文件上传功能
本篇文章,我们要来做一个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 文件上传功能的更多相关文章
- Spring +SpringMVC 实现文件上传功能。。。
要实现Spring +SpringMVC 实现文件上传功能. 第一步:下载 第二步: 新建一个web项目导入Spring 和SpringMVC的jar包(在MyEclipse里有自动生成spring ...
- spring mvc 3.0 实现文件上传功能
http://club.jledu.gov.cn/?uid-5282-action-viewspace-itemid-188672 —————————————————————————————————— ...
- springmvc中使用文件上传功能
项目代码:https://github.com/PeiranZhang/springmvc-fileupload Servlet3.0之前使用文件上传功能 Servlet3.0之前需要使用common ...
- PHPCMS_V9 模型字段添加单文件上传功能
后台有“多文件上传”功能,但是对于有些情况,我们只需要上传一个文件,而使用多文件上传功能上传一个文件,而调用时调用一个文件URL太麻烦了. 使用说明: 1.打开phpcms\modules\conte ...
- 配置php.ini实现PHP文件上传功能
本文介绍了如何配置php.ini实现PHP文件上传功能.其中涉及到php.ini配置文件中的upload_tmp_dir.upload_max_filesize.post_max_size等选项,这些 ...
- MVC5:使用Ajax和HTML5实现文件上传功能
引言 在实际编程中,经常遇到实现文件上传并显示上传进度的功能,基于此目的,本文就为大家介绍不使用flash 或任何上传文件的插件来实现带有进度显示的文件上传功能. 基本功能:实现带有进度条的文件上传功 ...
- Spring文件上传出错:java.lang.ClassCastException: org.apache.catalina.connector.Request
java.lang.ClassCastException: org.apache.catalina.connector.RequestFacade cannot be cast to org.spri ...
- 用c++开发基于tcp协议的文件上传功能
用c++开发基于tcp协议的文件上传功能 2005我正在一家游戏公司做程序员,当时一直在看<Windows网络编程> 这本书,把里面提到的每种IO模型都试了一次,强烈推荐学习网络编程的同学 ...
- Node.js新手教程——怎样实现文件上传功能
作者:zhanhailiang 日期:2014-11-16 本文将介绍怎样使用Node.js实现文件上传功能. 1. 初始化项目信息:npm init [root@~/wade/nodejs/node ...
随机推荐
- 一个Java Dao测试用例
import static org.junit.Assert.assertTrue; import java.util.Date; import java.util.HashMap; import j ...
- ionic —— 开发环境搭建并编译运行第一个APP
其实类似的环境已经玩了很多次了,最开始玩还是微信刚刚出来,那会儿没有智能机.只好安装一个模拟器,却只是为了注册一个微信.想想也就是够了~ 前前后后折腾了很多次,可是每一次都给人不一样的感觉,也许是这个 ...
- Bootstrap系列 -- 7. 列表排版方式
一. 去点列表 1. 使用class=list-unstyled <ul > <li>无序列表项目</li> <li>无序列表项目</li> ...
- .net框架中少有人知的扩展cmod
最近在利用metadata api抽取.net的原数据信息,发现了不少“坑”,也发现了不少常年用着c#的人都不知道的扩展. 说到.net原数据的可扩展性,第一个让人能想到的就是CustomAttrib ...
- 使用Python 将shapefile导入mongodb
使用Python 将shapefile导入mongodb 随着big data时代的到来,各个行业都在考虑能不能把big data的思路.方法引入进来,GIS行业也不能免俗. 下面就介绍一下如何将sh ...
- STM32 C语言,端口映射
static XX 有记忆的定义 typedef XX 可以多次定义一个 #ifedf XXX XXX(程序段1) #else XXX(程序段2)
- ssh配置文件ssh_config和sshd_config区别
问题描述:在一次配置ssh端口和秘钥登录过程中,修改几次都没有成功.最后发现修改的是ssh.config,原因是习惯tab一下,实在是眼拙! ssh_config和sshd_config配置文件区别: ...
- [AJAX系列]onreadystatechange事件
onreadystatechange事件: 当请求被发送到服务器时,我们需要执行一些基于响应的任务 每当readyState改变时,就会触发onreadystatechange事件 readyStat ...
- Java--笔记(1)
1.Swing 是在AWT的基础上构建的一套新的图形界面系统,它提供了AWT 所能够提供的所有功能,并且用纯粹的Java代码对AWT 的功能进行了大幅度的扩充.AWT 是基于本地方法的C/C++程序, ...
- Java垃圾收集算法介绍
垃圾回收器GC(Garbage Collection) 一.引用计数算法(Reference Counting) 介绍:给对象添加一个引用计数器,每当一个地方引用它时,数据器加1:当引用失效时,计数器 ...