欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

springMVC配置环境实现文件上传和下载

程序员文章站 2024-03-11 17:41:07
最近的项目中用到了文件的上传和下载功能,我觉着这个功能比较重要,因此特意把它提取出来自己进行了尝试。 下面就是springmvc配置环境实现文件上传和下载的具体步骤,供大...

最近的项目中用到了文件的上传和下载功能,我觉着这个功能比较重要,因此特意把它提取出来自己进行了尝试。

下面就是springmvc配置环境实现文件上传和下载的具体步骤,供大家参考,具体内容如下

一、 基础配置:

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

<project xmlns="http://maven.apache.org/pom/4.0.0" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" 
 xsi:schemalocation="http://maven.apache.org/pom/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 
 <modelversion>4.0.0</modelversion> 
 <groupid>filloadtest</groupid> 
 <artifactid>filloadtest</artifactid> 
 <packaging>war</packaging> 
 <version>0.0.1-snapshot</version> 
 <name>filloadtest maven webapp</name> 
 <url>http://maven.apache.org</url> 
 <build> 
 <finalname>filloadtest</finalname> 
 <plugins> 
  <!-- 以下配置可以保证每次强制更新时jre版本不会变化,那我的eclipse4.4.1,maven3.2.5为例,如果不设置这个,每次强制更新时jre就会变回1.5 --> 
  <plugin> 
  <artifactid>maven-compiler-plugin</artifactid> 
  <version>2.3.2</version> 
  <configuration> 
   <source>1.7</source> 
   <target>1.7</target> 
   <encoding>utf-8</encoding> 
   <compilerarguments> 
   <verbose /> 
   <bootclasspath>${java.home}\lib\rt.jar</bootclasspath> 
   </compilerarguments> 
  </configuration> 
  </plugin> 
 </plugins> 
 </build> 
 <dependencies> 
 <dependency> 
 <groupid>junit</groupid> 
 <artifactid>junit</artifactid> 
 <version>3.8.1</version> 
 <scope>test</scope> 
 </dependency> 
 <dependency> 
 <groupid>org.springframework</groupid> 
 <artifactid>spring-webmvc</artifactid> 
 <version>4.0.6.release</version> 
 </dependency> 
 <dependency> 
 <groupid>com.fasterxml.jackson.core</groupid> 
 <artifactid>jackson-annotations</artifactid> 
 <version>2.2.3</version> 
 </dependency> 
 <dependency> 
 <groupid>com.fasterxml.jackson.core</groupid> 
 <artifactid>jackson-core</artifactid> 
 <version>2.2.3</version> 
 </dependency> 
 <dependency> 
 <groupid>com.fasterxml.jackson.core</groupid> 
 <artifactid>jackson-databind</artifactid> 
 <version>2.2.3</version> 
 </dependency> 
 <dependency> 
 <groupid>commons-fileupload</groupid> 
 <artifactid>commons-fileupload</artifactid> 
 <version>1.3.1</version> 
 </dependency> 
 <dependency> 
 <groupid>commons-io</groupid> 
 <artifactid>commons-io</artifactid> 
 <version>2.4</version> 
 </dependency> 
 </dependencies> 
</project> 

web.xml基础配置:

<?xml version="1.0" encoding="utf-8"?> 
<web-app xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" 
 xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
 xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
 id="webapp_id" version="2.5"> 
 <filter> 
 <description>字符集过滤器</description> 
 <filter-name>encodingfilter</filter-name> 
 <filter-class>org.springframework.web.filter.characterencodingfilter</filter-class> 
 <init-param> 
  <description>字符集编码</description> 
  <param-name>encoding</param-name> 
  <param-value>utf-8</param-value> 
 </init-param> 
 </filter> 
 <filter-mapping> 
 <filter-name>encodingfilter</filter-name> 
 <url-pattern>/*</url-pattern> 
 </filter-mapping> 
 <servlet> 
 <servlet-name>springmvc</servlet-name> 
 <servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class> 
 <init-param> 
  <param-name>contextconfiglocation</param-name> 
  <param-value>classpath:spring.xml</param-value> 
 </init-param> 
 </servlet> 
 <servlet-mapping> 
 <servlet-name>springmvc</servlet-name> 
 <url-pattern>*.do</url-pattern> 
 </servlet-mapping> 
 <welcome-file-list> 
 <welcome-file>index.html</welcome-file> 
 <welcome-file>index.htm</welcome-file> 
 <welcome-file>index.jsp</welcome-file> 
 <welcome-file>default.html</welcome-file> 
 <welcome-file>default.htm</welcome-file> 
 <welcome-file>default.jsp</welcome-file> 
 </welcome-file-list> 
</web-app> 

spring基础配置spring.xml:

<?xml version="1.0" encoding="utf-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
 xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:p="http://www.springframework.org/schema/p" 
 xmlns:context="http://www.springframework.org/schema/context" 
 xmlns:mvc="http://www.springframework.org/schema/mvc" 
 xsi:schemalocation=" 
 http://www.springframework.org/schema/beans 
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
 http://www.springframework.org/schema/context 
 http://www.springframework.org/schema/context/spring-context-3.0.xsd 
 http://www.springframework.org/schema/mvc 
 http://www.springframework.org/schema/mvc/spring-mvc.xsd"> 
 
 
 <context:annotation-config /> 
 <mvc:annotation-driven /> 
 <context:component-scan base-package="controllers" /> 
 
 <!-- 避免ie执行ajax时,返回json出现下载文件 --> 
 <bean id="mappingjacksonhttpmessageconverter" 
 class="org.springframework.http.converter.json.mappingjackson2httpmessageconverter"> 
 <property name="supportedmediatypes"> 
  <list> 
  <value>text/html;charset=utf-8</value> 
  </list> 
 </property> 
 </bean> 
 
 
 <!-- 启动spring mvc的注解功能,完成请求和注解pojo的映射 --> 
 <bean 
 class="org.springframework.web.servlet.mvc.annotation.annotationmethodhandleradapter"> 
 <property name="messageconverters"> 
  <list> 
  <ref bean="mappingjacksonhttpmessageconverter" /><!-- json转换器 --> 
  </list> 
 </property> 
 </bean> 
 
 <!-- 支持上传文件 --> 
 <bean id="multipartresolver" 
 class="org.springframework.web.multipart.commons.commonsmultipartresolver" > 
 <!-- 100m --> 
 <property name="maxuploadsize" value="104857600"></property> 
 <property name="defaultencoding" value="utf-8"></property> 
 </bean> 
</beans> 

二、文件上传的代码

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

<!doctype html> 
<html> 
<head> 
 <meta http-equiv="content-type" content="text/html; charset=utf-8" /> 
</head> 
<body> 
 <form action="./uploadfile.do" method="post" enctype="multipart/form-data"> 
   选择文件:<input type="file" name="file"/> 
   <input type="submit" value="提交"/> 
 </form> 
</body> 
</html> 

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

package controllers; 
 
 
import java.io.file; 
import java.io.ioexception; 
import java.util.iterator; 
import javax.servlet.http.httpservletrequest; 
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.multipart.multipartfile; 
import org.springframework.web.multipart.multiparthttpservletrequest; 
import org.springframework.web.multipart.commons.commonsmultipartresolver; 
 
 
@controller 
public class filecontroller { 
 
 
 /** 
 * 文件上传 
 * 
 * @author:tuzongxun 
 * @title: uploadfile 
 * @param @param file 
 * @param @param request 
 * @param @throws illegalstateexception 
 * @param @throws ioexception 
 * @return void 
 * @date apr 28, 2016 1:22:00 pm 
 * @throws 
 */ 
 @requestmapping(value = "/uploadfile.do", method = requestmethod.post) 
 public void uploadfile(httpservletrequest request) 
  throws illegalstateexception, ioexception { 
 // @requestparam("file") multipartfile file, 
 commonsmultipartresolver multipartresolver = new commonsmultipartresolver( 
  request.getsession().getservletcontext()); 
 // 判断 request 是否有文件上传,即多部分请求 
 if (multipartresolver.ismultipart(request)) { 
  // 转换成多部分request 
  multiparthttpservletrequest multirequest = (multiparthttpservletrequest) request; 
  // 取得request中的所有文件名 
  iterator<string> iter = multirequest.getfilenames(); 
  while (iter.hasnext()) { 
  // 取得上传文件 
  multipartfile f = multirequest.getfile(iter.next()); 
  if (f != null) { 
   // 取得当前上传文件的文件名称 
   string myfilename = f.getoriginalfilename(); 
   // 如果名称不为“”,说明该文件存在,否则说明该文件不存在 
   if (myfilename.trim() != "") { 
   // 定义上传路径 
   string path = "c:\\users\\tuzongxun123\\desktop\\" 
    + myfilename; 
   file localfile = new file(path); 
   f.transferto(localfile); 
   } 
  } 
  } 
 } 
 } 
} 

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

springMVC配置环境实现文件上传和下载

三、文件下载

文件下载需要获取下载文件的存储路径,这里只是手动填入,如果是在具体项目中,可以把文件名和上传后的存储路径保存在数据库中。然后增加一个文件列表的页面展示文件名和文件路径,然后点击下载的时候把相应的文件名和路径传到后台操作。

/** 
  * 文件下载,需要文件名和文件地址 
  * 
  * @author:tuzongxun 
  * @title: download 
  * @param@param name 
  * @param@param path 
  * @param@return 
  * @param@throws ioexception 
  * @returnresponseentity<byte[]> 
  * @date apr 28,2016 1:21:32 pm 
  * @throws 
  */ 
 @requestmapping(value = "/downloadfile.do") 
 public responseentity<byte[]> download(@requestparam("name") string name, 
   @requestparam("filepath") string path) throws ioexception { 
  file file = new file(path); 
  httpheaders headers = new httpheaders(); 
  string filename = new string(name.getbytes("utf-8"), "iso-8859-1");// 为了解决中文名称乱码问题 
  headers.setcontentdispositionformdata("attachment", filename); 
  headers.setcontenttype(mediatype.application_octet_stream); 
  return new responseentity<byte[]>(fileutils.readfiletobytearray(file), 
    headers, httpstatus.created); 
 } 

html页面,这里只是简单的填写文件名和文件路径,用form表单提交到后台,然后后台会控制response在页面弹出保存文件路径的选择框,当然了,这里的后台我没有做什么处理,如果文件不存在是会报错的,可以进行相应的处理:
文件下载:  

 </br> </br> 
 <form action="./downloadfile.do"style="border:1px solid grey;width:auto;" method="post"> 
   文件名:<input type="text" name="name"/></br></br> 
   文件路径:<input type="text" name="filepath"/></br></br> 
   <input type="submit" value="确认下载"/> 
 </form> 

页面视图如下:

springMVC配置环境实现文件上传和下载

如果文件不存在,报错如下:

springMVC配置环境实现文件上传和下载

以上就是本文的全部内容,希望对大家的学习有所帮助。