Spring MVC实现文件的上传下载

Spring XML的文件上传配置:

   1. 首先配置Spring MVC对json解析的中文内容的支持

   

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="messageConverters">
			<list>
				<ref bean="mappingJacksonHttpMessageConverter" />
			</list>
		</property>
	</bean>
	<bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
		<property name="supportedMediaTypes">
			<list>
				<value>application/json;charset=UTF-8</value>
			</list>
		</property>
	</bean>

    2. 上传配置:

<!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="defaultEncoding" value="UTF-8" />
		<!-- 指定所上传文件的总大小不能超过200KB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->
		<property name="maxUploadSize" value="20000000" />
	</bean>

	<!-- SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException -->
	<!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 -->
	<bean id="exceptionResolver"
		class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
		<property name="exceptionMappings">
			<props>
				<!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到/WEB-INF/jsp/error_fileupload.jsp页面 -->
				<prop
					key="org.springframework.web.multipart.MaxUploadSizeExceededException">error_fileupload</prop>
			</props>
		</property>
	</bean>

    3. controller中的文件上传和下载的处理:

    

package com.focoon.web.controller;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
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;

import com.focoon.utils.FileOprUtils;

@Controller
@RequestMapping("/attachment")
public class AttachmentController {
	
	@RequestMapping(value="/edit",method=RequestMethod.GET)
	public String add() {
		return "attachment/edit";
	}
	
	@RequestMapping(value="/upload",method=RequestMethod.POST)
	public @ResponseBody Map upload(@RequestParam MultipartFile[] myfiles, 
			String fileType, String fileDesc) throws Exception {
		  String fileName = myfiles[0].getOriginalFilename();
		  System.out.println("myfile name = " + fileName);
		  System.out.println("myfile size = " + myfiles[0].getSize());
		  System.out.println("fileType = " + fileType);
		  System.out.println("fileDesc = " + fileDesc);
		  String path = "C:/upload_file/"+fileName;
		  FileOprUtils.copyFileToServerPath(path, myfiles[0].getInputStream());
		  Map<String, String> resultMap = new HashMap<String, String>();
		  resultMap.put("fileName", fileName);
		  return resultMap;
	}
	
	@RequestMapping(value = "/download", method = RequestMethod.GET)
	public ResponseEntity<byte[]> downloadImage(String fileName) throws Exception {
		// 根据id找到文件的保存路径
		String imgPath = "C:/upload_file/"+fileName;
		File file=new File(imgPath);  
        HttpHeaders headers = new HttpHeaders();    
        String filename = new String(fileName.getBytes("gbk"),"iso-8859-1");
        headers.setContentDispositionFormData("attachment", filename);   
        headers.setContentType(MediaType.IMAGE_JPEG);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),    
                                          headers, HttpStatus.OK);  
	}
	
}

  最后是页面的提交,页面提交可以是异步的形式

  

  这里我使用了easyui中的form库,支持无刷新文件上传,同时这里实现了对上传文件的本地预览和异步下载功能

   
Spring MVC实现文件的上传下载
 

   spring中用到的jar包列举如下:

   commons-fileupload-1.3.jar

commons-io-2.4.jar

commons-lang3-3.3.2.jar

commons-logging-1.2.jar

jackson-core-asl-1.5.0.jar

jackson-mapper-asl-1.5.0.jar

jstl-1.2.jar

org.springframework.web-3.0.6.RELEASE.jar

org.springframework.web.servlet-3.0.6.RELEASE.jar

servlet-api.jar

spring-asm-3.0.6.RELEASE.jar

spring-beans-3.0.6.RELEASE.jar

spring-context-3.0.6.RELEASE.jar

spring-core-3.0.6.RELEASE.jar

spring-expression-3.0.6.RELEASE.jar

最后是除了jar包之外的源代码:

相关推荐