SpringMVC—另一种方式文件上传

jopen 6年前

web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
xmlns="http://java.sun.com/xml/ns/javaee"&nbsp;
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&nbsp;
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee&nbsp;
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"&gt;

 <!-- 配置DispatcherServlet -->
 <servlet>
  <servlet-name>commServlet</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <!-- 手动配置加载的配置文件 -->
  <init-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/classes/spring/.xml</param-value>
  </init-param>
  <!-- 项目启动时加载 -->
  <load-on-startup>1</load-on-startup>
 </servlet>

 <!-- servlet映射 -->
 <servlet-mapping>
  <!-- 所有.php结尾的请求都由commServlet管理  -->
  <servlet-name>commServlet</servlet-name>
  <url-pattern>
.php</url-pattern>
 </servlet-mapping>

 <!-- 配置编码过滤器 -->
 <filter>
  <filter-name>EncodingFilter</filter-name>
  <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  <!-- 初始化参数,编码是UTF-8 -->
  <init-param>
  <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>

 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
</web-app>


servlet.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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
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-3.0.xsd   
          http://www.springframework.org/schema/util    
          http://www.springframework.org/schema/util/spring-util-3.0.xsd"&gt;




<!-- 主键扫描,配置要扫描的Java类 -->
<context:component-scan base-package="com.cjh.action" />


<!-- 定义一个视图解析类,基于ResourceView的解析器 ,此解析器是在url解析器上,加入了对jstl的支持-->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/jsp/" />
<!-- 后缀 -->
<property name="suffix" value=".jsp" />


</bean>








<!-- 处理文件上传 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 默认编码 (ISO-8859-1) -->
<property name="defaultEncoding" value="utf-8" />
<!-- 最大内存大小 (10240)-->
<property name="maxInMemorySize" value="10240" />
<!-- 上传后的临时目录名 (WebUtils#TEMP_DIR_CONTEXT_ATTRIBUTE) -->
<property name="uploadTempDir" value="/upload_temp/" />
<!-- 最大文件大小,-1为无限止(-1),注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和  -->
<property name="maxUploadSize" value="-1" />

</bean>




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


</beans>


action类:
package com.cjh.action;


import java.io.File;
import java.util.UUID;


import javax.servlet.ServletContext;


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.context.ServletContextAware;
import org.springframework.web.multipart.commons.CommonsMultipartFile;




/**
 
文件上传类,实现ServletContextAware可以获得servlet上下文
 /
@Controller
public class FileUploadAction  implements ServletContextAware{


/setvlet上下文对象/
private ServletContext servletContext;

/提供对应的set方法,SpringMVC会自动的注入/
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}






/**
文件上传
@param file
@return
*/
@RequestMapping(value="/handleFormUpload",method=RequestMethod.POST)
public String fileUpload(@RequestParam("file")CommonsMultipartFile file){
/判断文件是否为空,空直接返回上传错误/
if(!file.isEmpty()){
/获取本地文件存储目录/
String path = servletContext.getRealPath("/fileupload/");
/获得文件名/
String fileName = file.getOriginalFilename();
/获得文件后缀名/
String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
/拼接文件路径,以UUID生成文件名/
String filePath = path + File.separator + UUID.randomUUID().toString()+ suffix;
/创建一个要保存的新文件/
File saveFile = new File(filePath);

try{
/将文件写入到新文件中/
file.getFileItem().write(saveFile);

}catch(Exception e ){
e.printStackTrace();
return "fileError";
}

return "fileUploadSuccess";


}else{
return "fileError";
}

}
}