SSM+maven实现多文件上传和文件下载

 第一步,在pom.xml中导入jar包:java

<!-- 文件上传组件 -->
<dependency>
	<groupId>commons-fileupload</groupId>
	<artifactId>commons-fileupload</artifactId>
	<version>1.3.1</version>
</dependency>

 第二步,在springmvc.xml中定义文件上传解析器:web

<!-- 定义文件上传解析器 -->
<bean id="multipartResolver"                        
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
	<!-- 设定默认编码 -->
	<property name="defaultEncoding" value="UTF-8"/>
	<!-- 设定文件上传的最大值(全部文件的容量之和)8MB,8*1024*1024 -->
	<property name="maxUploadSize" value="8388608"></property>
	<!-- 设置在文件上传时容许写到内存中的最大值,上传文件大小若小于此参数,则不会生成临时文件 -->
	<property name="maxInMemorySize" value="2048"></property>
</bean>

第三步,编写测试文件上传和下载的表单,注意,文件上传的表单必须添加enctype="multipart/form-data",即设置将文件以二进制形式上传;若是须要进行多文件上传,则需在input file后添加"multiple='multiple'":spring

<!--文件上传-->
<form action="/file/upload" method="post" enctype="multipart/form-data">
	文件上传:<input type="file" name="file" multiple="multiple"><br>
	<input type="submit" value="提交">
</form>

<!--文件下载-->
<form action="/file/download" method="post" >
	文件名:<input type="text" name="filename"><br>
	文件路径:<input type="text" name="path"><br>
	<input type="submit" value="下载">	
</form>

第四步,在配置文件resource.properties中设置上传后文件的存放位置,固然也能够直接在代码中直接写,但这样作不方便以后更改路径:mvc

#文件存放位置
CONTEXT_DOCBASE=D:/file
CONTEXT_PACH=/file

第五步,在springmvc.xml文件中配置扫描properties文件:app

<context:property-placeholder location="classpath:resource.properties" />

此处注意:若是有多个properties文件须要配置扫描时,不能直接写多个<context:property-placeholder location="classpath:resource.properties" />,在这种状况下,有如下三种解决方法:dom

(1)若是配置文件都为properties文件,则在扫描配置时能够直接书写<context:property-placeholder location="classpath*:*.properties" />.post

(2)在spring 2.5中,能够使用如下代码实现扫描配置:测试

<bean class="org.springframework.beans.factory.config.PropertyPlaceh olderConfigurer">  

    <property name="location" value="xxx.properties" />  

    <property name="ignoreUnresolvablePlaceholders" value="true/> 

</bean> 

(3)在spring3.0中,能够在每一个扫描配置语句后面添加ignore-unresolvable=”true”.编码

<context:property-placeholder location=”” ignore-unresolvable=”true”>spa

第六步,开始文件上传Controller层代码的编写,其中MultipartFile[ ] files表示接收多个文件,支持多文件上传,IDUtils为自动生成随机的,惟一的文件名,return Result.ok()为返回一个状态码为200的上传成功标识。

IDUtils.java:

public class IDUtils {

	/**
	 * 文件名生成
	 */
	public static String getFileName() {
		// 取当前时间的长整形值包含毫秒
		long millis = System.currentTimeMillis();
		// long millis = System.nanoTime();
		// 加上三位随机数
		Random random = new Random();
		int end3 = random.nextInt(999);
		// 若是不足三位前面补0
		String str = millis + String.format("%03d", end3);

		return str;
	}

}
//从resource.properties文件中将文件存放路径读取出
@Value("${CONTEXT_DOCBASE}")
private String CONTEXT_DOCBASE;

@RequestMapping("/file/upload")
@ResponseBody
public Result uploadFile(@RequestParam("file") MultipartFile[] files) throws 
    IllegalStateException, IOException{
	//上传文件路径
	String rootPath=CONTEXT_DOCBASE;
	for (MultipartFile file : files) {
			
		//原始名称
		String originalFileName=file.getOriginalFilename();
		//文件扩展名
		String ext=FilenameUtils.getExtension(originalFileName);
		//新文件名
		String newFileName=IDUtils.getFileName();
		//新文件
		File newFile=new File(rootPath+File.separator+newFileName+"."+ext);
		//判断目标文件所在目录是否存在
		if(!newFile.getParentFile().exists()){
			//若是目标文件所在的目录不存在,则建立父目录
			newFile.getParentFile().mkdirs();
		}
		System.out.println(newFile);
		//将内存中的数据写入磁盘
		file.transferTo(newFile);
		System.out.println("文件上传成功!");
		}
		return Result.ok();
	}

第七步,文件下载Controller层代码的编写:

//文件下载
@RequestMapping(value="/file/download")
public ResponseEntity<byte[]> downLoad(@RequestParam(value="filename")String 
    filename,@RequestParam("path")String path) throws Exception{
    File file=new File(path);
	HttpHeaders headers=new HttpHeaders();
	String name=new String(filename.getBytes("UTF-8"),"iso-8859-1");
	headers.setContentDispositionFormData("attachment", name);
	headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
	return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers,HttpStatus.CREATED);
}

最后一步,测试结果:

文件上传:

文件下载: