---
title: "fastupload-springmvc 0.5.5发布"
author: "Mojarra"
date: "2013-04-15T21:55:58Z"
tags: []
categories: ["企业架构"]
slug: "fastupload-springmvc-0-5-5"
draft: false
lastmod: "2013-04-15T21:55:58Z"
id: 1847886
url: "https://mojarra.iteye.com/blog/1847886"
---

fastupload-springmvc是利用fastupload开源组件Spring MVC框架写的文件上传插件，使用此插件，能在Controller中以注解的方式来获取上传的文件，然后对其进行操作。比使用fastupload核心API更加简洁。使用方式如下：

在pom.xml文件中加入fastupload-springmvc的依赖，因Spring MVC框架本身只到3.1.0才支持非文件类型的MultipartFile，所以使用此插件，最好是基于Spring MVC 3.1.0或者更高版本做开发

```
<dependency>
<groupId>net.sf.fastupload</groupId>
<artifactId>fastupload-springmvc</artifactId>
<version>0.5.5</version>
</dependency>
```

 

在spring mvc的配置文件中增加FastuploadResolver Bean定义，这里使用注解的方式，使用XML配置文件与此类似，bean的名称和属性是一样的

```
@Bean(name = "multipartResolver")
	public MultipartResolver getMultipartResolver() {
		FastuploadResolver fastuploadResolver = new FastuploadResolver();
		// 1, set the max content length of HTTP request
		fastuploadResolver.setMaxContentLength(2000000);
		// 2, limit 1M size for a file
		fastuploadResolver.setThreshold(1024 * 1024);
		// 3, FastuploadResolver don't use temporary repository in default. It
		// use the WEB APP tmp directory define in Spring MVC when set the
		// property as true. but you can set the tmp dirctory via
		// <em>setTempRepository(String repository)</em> method
		fastuploadResolver.setUseTempRepository(false);
		return fastuploadResolver;
	}
```

 上面的代码处1，设置HTTP请求总长度不超过2000000，代码处2，限制文件不超过1M，代码处3，使用内存解析模式，如果设置了使用磁盘解析模式，此属性设置为true，也可以指定临时文件的存放路径，不指定的情况下，使用当前Spring MVC WEB APP的默认临时目录。

 

最后，写一个Controller测试，这里有一点需要强调，Fastupload插件是支持非文件类型数据的

```
@Controller
public class UploadController {

	@RequestMapping(value = "/upload", method = { RequestMethod.POST })
	@ResponseBody
	public String upload(@RequestParam("desc") String desc,
			@RequestParam("file") MultipartFile file) {
		 
		/*
		 * use the <em>file</em> object directly
		 */
		return (desc != null && !file.isEmpty()) ? "success" : "failure";
	}
}
```

 至此，在Spring MVC中使用fastupload的Controller代码变得清静了。

项目地址：https://sourceforge.net/projects/fastupload/

完整的demo：http://sourceforge.net/projects/fastupload/files/net.sf.fastupload.multipart.resolver-demo.zip/download，下载后，使用mvn jetty:run启动web服务器，然后在浏览器中输入http://localhost:8080/resources/file.html

 

@仪山湖