基于spring 3.0mvc 框架的文件上传实现
Spring 框架提供了构建 Web 应用程序的全功能 MVC 模块。使用 Spring 可插入的 MVC 架构,可以选择是使用内置的 Spring Web 框架还是 Struts 这样的 Web 框架。通过策略接口,Spring 框架是高度可配置的,而且包含多种视图技术,例如 JavaServer Pages(JSP)技术、Velocity、Tiles、iText 和 POI。Spring MVC 框架并不知道使用的视图,所以不会强迫您只使用 JSP 技术。Spring MVC 分离了控制器、模型对象、分派器以及处理程序对象的角色,这种分离让它们更容易进行定制。
第一步:1. spring使用了apache-commons下得上传组件,因此,我们需要引入两个jar包:
- apache-commons-fileupload.jar
- apache-commons-io.jar
第二步:2. 在springmvc-servlet.xml配置文件中,增加CommonsMultipartResoler配置:
<?xml version="1.0" encoding="UTF-8" ?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <!-- 扫描包 --> <context:component-scan base-package="com.tgb.web.controller.annotation"/> <!-- 启用注解包 --> <mvc:annotation-driven/> <!-- 被上面替代 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"></bean> <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean> --> <!-- 视图解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/" /> <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"/> <!-- 最大文件大小,-1为无限止(-1) --> <property name="maxUploadSize" value="20000000000"/> <!-- 最大内存大小 (10240)--> <property name="maxInMemorySize" value="200000"/> </bean> <!-- 静态资源访问 --> <!-- <mvc:resources location="/images/" mapping="/images/**"/>--> </beans>
第三步:配置web.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app version="2.5" 3 xmlns="http://java.sun.com/xml/ns/javaee" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 6 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> 7 8 9 10 <welcome-file-list> 11 <welcome-file>index.jsp</welcome-file> 12 </welcome-file-list> 13 14 <servlet> 15 <servlet-name>springMVC</servlet-name> 16 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 17 <init-param> 18 <param-name>contextConfigLocation</param-name> 19 <param-value>classpath*:config/springMVC-servlet.xml</param-value> 20 </init-param> 21 <load-on-startup>1</load-on-startup> 22 </servlet> 23 24 <!-- 解决乱码 --> 25 <filter> 26 <filter-name>encodingFilter</filter-name> 27 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 28 <init-param> 29 <param-name>encoding</param-name> 30 <param-value>UTF-8</param-value> 31 </init-param> 32 <init-param> 33 <param-name>froceEncoding</param-name> 34 <param-value>true</param-value> 35 </init-param> 36 </filter> 37 38 <filter-mapping> 39 <filter-name>encodingFilter</filter-name> 40 <url-pattern>/*</url-pattern> 41 </filter-mapping> 42 43 44 45 <servlet-mapping> 46 <servlet-name>springMVC</servlet-name> 47 <url-pattern>/</url-pattern> 48 </servlet-mapping> 49 </web-app>
第四步:建立upload.jsp页面,内容如下:
1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 %> 6 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 8 <html> 9 <head> 10 <base href="<%=basePath%>"> 11 12 <title>测试springmvc中上传的实现</title> 13 <meta http-equiv="pragma" content="no-cache"> 14 <meta http-equiv="cache-control" content="no-cache"> 15 <meta http-equiv="expires" content="0"> 16 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 17 <meta http-equiv="description" content="This is my page"> 18 <!-- 19 <link rel="stylesheet" type="text/css" href="styles.css"> 20 --> 21 </head> 22 23 <body> 24 <form action="uploadContoller?toupload" method="post" enctype="multipart/form-data"> 25 文件上传:<input type="file" value="" name="file"> 26 <input type="submit" value="上传"/> 27 </form> 28 </body> 29 </html>
建立控制器UploadContoller.java(三种方法支持文件上传),代码如下:
package com.tgb.web.controller.annotation; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.Iterator; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; 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.CommonsMultipartFile; import org.springframework.web.multipart.commons.CommonsMultipartResolver; @Controller @RequestMapping("/uploadContoller") public class UploadContoller { //========================第一种:====================== @RequestMapping(params="uploadUser") // 普通上传 public String uploadUser(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException { System.out.println("filename++++++++" + file.getOriginalFilename()); if (!file.isEmpty()) { try { Date date = new Date(); FileOutputStream os = new FileOutputStream("../images" + date.getTime() + file.getOriginalFilename()); InputStream in = file.getInputStream(); int b = 0; while ((b = in.read()) != -1) { os.write(b); } os.flush(); os.close(); in.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return "success"; } //========================第二种:====================== @RequestMapping(params="toupload") public String toupload(HttpServletRequest request, HttpServletResponse response) { // 创建一个通用的多部分解析器 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()) { // 记录上传过程起始时的时间,用来计算上传时间 int pre = (int) System.currentTimeMillis(); // 取得上传文件 MultipartFile file = multiRequest.getFile(iter.next()); if (file != null) { // 取得当前上传文件的文件名称 String myFileName = file.getOriginalFilename(); // 如果名称不为“”,说明该文件存在,否则说明该文件不存在 if (myFileName.trim() != "") { System.out.println(myFileName); // 重命名上传后的文件名 String fileName = "demoUpload" + file.getOriginalFilename(); // 定义上传路径 String path = "/images/" + fileName; File localFile = new File(path); try { file.transferTo(localFile); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } // 记录上传该文件后的时间 int finaltime = (int) System.currentTimeMillis(); System.out.println(finaltime - pre); } } return "success"; } //========================第三种:====================== @RequestMapping(params="niceupload") // 优化上传 public String niceupload(HttpServletRequest request, HttpServletResponse response) { CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver( request.getSession().getServletContext()); if (multipartResolver.isMultipart(request)) { MultipartHttpServletRequest mulitRequest = (MultipartHttpServletRequest) (request); Iterator<String> iterator = mulitRequest.getFileNames(); while (iterator.hasNext()) { MultipartFile fiel = mulitRequest.getFile((String) iterator .next()); if (fiel != null) { String fileName = "demoUpload" + fiel.getOriginalFilename(); String path = "D:/" + fileName; File localfile = new File(path); try { fiel.transferTo(localfile); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } return "/success"; } }
5. 建立success.jsp页面
<%@ page language="java" import="java.util.*" contentType="text/html;charset=utf-8" pageEncoding="utf-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>传递参数</title> </head> <body> <h1>上传成功 +++++++++++</h1> </body> </html>
3、 进入项目发布后的目录,发现文件上传成功:
您可以通过点击 右下角 的按钮 来对文章内容作出评价, 也可以通过左下方的 关注按钮 来关注我的博客的最新动态。
如果文章内容对您有帮助, 不要忘记点击右下角的 推荐按钮 来支持一下哦
如果您对文章内容有任何疑问, 可以通过评论或发邮件的方式联系我: 2276292708@qq.com或加入JAVA技术交流群:306431857
如果需要转载,请注明出处,谢谢!!
责任重于泰山,任重而道远。