使用springMVC实现文件上传和下载之环境配置与上传

时间:2023-03-03 11:21:26

最近的项目中用到了文件的上传和下载功能,任务分配给了其他的同时完成。如今项目结束告一段落,我觉着这个功能比较重要,因此特意把它提取出来自己进行了尝试。

一、 基础配置:

maven导包及配置pom.xml,导包时除开springmvc的基础依赖外,需要导入文件上传下载时用到的commons-io.jsr和commons-fileupload.jar:

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3. <modelVersion>4.0.0</modelVersion>
  4. <groupId>filLoadTest</groupId>
  5. <artifactId>filLoadTest</artifactId>
  6. <packaging>war</packaging>
  7. <version>0.0.1-SNAPSHOT</version>
  8. <name>filLoadTest Maven Webapp</name>
  9. <url>http://maven.apache.org</url>
  10. <build>
  11. <finalName>filLoadTest</finalName>
  12. <plugins>
  13. <!-- 以下配置可以保证每次强制更新时jre版本不会变化,那我的eclipse4.4.1,maven3.2.5为例,如果不设置这个,每次强制更新时jre就会变回1.5 -->
  14. <plugin>
  15. <artifactId>maven-compiler-plugin</artifactId>
  16. <version>2.3.2</version>
  17. <configuration>
  18. <source>1.7</source>
  19. <target>1.7</target>
  20. <encoding>UTF-8</encoding>
  21. <compilerArguments>
  22. <verbose />
  23. <bootclasspath>${java.home}\lib\rt.jar</bootclasspath>
  24. </compilerArguments>
  25. </configuration>
  26. </plugin>
  27. </plugins>
  28. </build>
  29. <dependencies>
  30. <dependency>
  31. <groupId>junit</groupId>
  32. <artifactId>junit</artifactId>
  33. <version>3.8.1</version>
  34. <scope>test</scope>
  35. </dependency>
  36. <dependency>
  37. <groupId>org.springframework</groupId>
  38. <artifactId>spring-webmvc</artifactId>
  39. <version>4.0.6.RELEASE</version>
  40. </dependency>
  41. <dependency>
  42. <groupId>com.fasterxml.jackson.core</groupId>
  43. <artifactId>jackson-annotations</artifactId>
  44. <version>2.2.3</version>
  45. </dependency>
  46. <dependency>
  47. <groupId>com.fasterxml.jackson.core</groupId>
  48. <artifactId>jackson-core</artifactId>
  49. <version>2.2.3</version>
  50. </dependency>
  51. <dependency>
  52. <groupId>com.fasterxml.jackson.core</groupId>
  53. <artifactId>jackson-databind</artifactId>
  54. <version>2.2.3</version>
  55. </dependency>
  56. <dependency>
  57. <groupId>commons-fileupload</groupId>
  58. <artifactId>commons-fileupload</artifactId>
  59. <version>1.3.1</version>
  60. </dependency>
  61. <dependency>
  62. <groupId>commons-io</groupId>
  63. <artifactId>commons-io</artifactId>
  64. <version>2.4</version>
  65. </dependency>
  66. </dependencies>
  67. </project>

web.xml基础配置:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  4. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  5. id="WebApp_ID" version="2.5">
  6. <filter>
  7. <description>字符集过滤器</description>
  8. <filter-name>encodingFilter</filter-name>
  9. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  10. <init-param>
  11. <description>字符集编码</description>
  12. <param-name>encoding</param-name>
  13. <param-value>UTF-8</param-value>
  14. </init-param>
  15. </filter>
  16. <filter-mapping>
  17. <filter-name>encodingFilter</filter-name>
  18. <url-pattern>/*</url-pattern>
  19. </filter-mapping>
  20. <servlet>
  21. <servlet-name>springMVC</servlet-name>
  22. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  23. <init-param>
  24. <param-name>contextConfigLocation</param-name>
  25. <param-value>classpath:spring.xml</param-value>
  26. </init-param>
  27. </servlet>
  28. <servlet-mapping>
  29. <servlet-name>springMVC</servlet-name>
  30. <url-pattern>*.do</url-pattern>
  31. </servlet-mapping>
  32. <welcome-file-list>
  33. <welcome-file>index.html</welcome-file>
  34. <welcome-file>index.htm</welcome-file>
  35. <welcome-file>index.jsp</welcome-file>
  36. <welcome-file>default.html</welcome-file>
  37. <welcome-file>default.htm</welcome-file>
  38. <welcome-file>default.jsp</welcome-file>
  39. </welcome-file-list>
  40. </web-app>

spring基础配置spring.xml:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:mvc="http://www.springframework.org/schema/mvc"
  6. xsi:schemaLocation="
  7. http://www.springframework.org/schema/beans
  8. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  9. http://www.springframework.org/schema/context
  10. http://www.springframework.org/schema/context/spring-context-3.0.xsd
  11. http://www.springframework.org/schema/mvc
  12. http://www.springframework.org/schema/mvc/spring-mvc.xsd">
  13. <context:annotation-config />
  14. <mvc:annotation-driven />
  15. <context:component-scan base-package="controllers" />
  16. <!-- 避免IE执行AJAX时,返回JSON出现下载文件 -->
  17. <bean id="mappingJacksonHttpMessageConverter"
  18. class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
  19. <property name="supportedMediaTypes">
  20. <list>
  21. <value>text/html;charset=utf-8</value>
  22. </list>
  23. </property>
  24. </bean>
  25. <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
  26. <bean
  27. class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
  28. <property name="messageConverters">
  29. <list>
  30. <ref bean="mappingJacksonHttpMessageConverter" /><!-- json转换器 -->
  31. </list>
  32. </property>
  33. </bean>
  34. <!-- 支持上传文件 -->
  35. <bean id="multipartResolver"
  36. class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >
  37. <!-- 100M -->
  38. <property name="maxUploadSize" value="104857600"></property>
  39. <property name="defaultEncoding" value="utf-8"></property>
  40. </bean>
  41. </beans>

二、文件上传的代码

上传的简单页面index.html,要注意form表单提交时的entype的设置:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  5. </head>
  6. <body>
  7. <form action="./upLoadFile.do" method="post" enctype="multipart/form-data">
  8. 选择文件:<input type="file" name="file"/>
  9. <input type="submit" value="提交"/>
  10. </form>
  11. </body>
  12. </html>

上传对应的后台java代码,具体问题见注释:

  1. package controllers;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.util.Iterator;
  5. import javax.servlet.http.HttpServletRequest;
  6. import org.apache.commons.io.FileUtils;
  7. import org.springframework.http.HttpHeaders;
  8. import org.springframework.http.HttpStatus;
  9. import org.springframework.http.MediaType;
  10. import org.springframework.http.ResponseEntity;
  11. import org.springframework.stereotype.Controller;
  12. import org.springframework.web.bind.annotation.RequestMapping;
  13. import org.springframework.web.bind.annotation.RequestMethod;
  14. import org.springframework.web.bind.annotation.RequestParam;
  15. import org.springframework.web.multipart.MultipartFile;
  16. import org.springframework.web.multipart.MultipartHttpServletRequest;
  17. import org.springframework.web.multipart.commons.CommonsMultipartResolver;
  18. @Controller
  19. public class fileController {
  20. /**
  21. * 文件上传
  22. *
  23. * @author:tuzongxun
  24. * @Title: upLoadFile
  25. * @param @param file
  26. * @param @param request
  27. * @param @throws IllegalStateException
  28. * @param @throws IOException
  29. * @return void
  30. * @date Apr 28, 2016 1:22:00 PM
  31. * @throws
  32. */
  33. @RequestMapping(value = "/upLoadFile.do", method = RequestMethod.POST)
  34. public void upLoadFile(HttpServletRequest request)
  35. throws IllegalStateException, IOException {
  36. // @RequestParam("file") MultipartFile file,
  37. CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
  38. request.getSession().getServletContext());
  39. // 判断 request 是否有文件上传,即多部分请求
  40. if (multipartResolver.isMultipart(request)) {
  41. // 转换成多部分request
  42. MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
  43. // 取得request中的所有文件名
  44. Iterator<String> iter = multiRequest.getFileNames();
  45. while (iter.hasNext()) {
  46. // 取得上传文件
  47. MultipartFile f = multiRequest.getFile(iter.next());
  48. if (f != null) {
  49. // 取得当前上传文件的文件名称
  50. String myFileName = f.getOriginalFilename();
  51. // 如果名称不为“”,说明该文件存在,否则说明该文件不存在
  52. if (myFileName.trim() != "") {
  53. // 定义上传路径
  54. String path = "C:\\Users\\tuzongxun123\\Desktop\\"
  55. + myFileName;
  56. File localFile = new File(path);
  57. f.transferTo(localFile);
  58. }
  59. }
  60. }
  61. }
  62. }
  63. }

页面效果图如下,当选择文件提交后,便会看到选中的文件被传到了代码中指定的位置,这里是我的桌面上。

使用springMVC实现文件上传和下载之环境配置与上传