基于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包:

  1. apache-commons-fileupload.jar
  2. 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

 <?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list> <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*:config/springMVC-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet> <!-- 解决乱码 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>froceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter> <filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

第四步:建立upload.jsp页面,内容如下:

 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>测试springmvc中上传的实现</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head> <body>
<form action="uploadContoller?toupload" method="post" enctype="multipart/form-data">
文件上传:<input type="file" value="" name="file">
<input type="submit" value="上传"/>
</form>
</body>
</html>

基于spring 3.0mvc 框架的文件上传实现

建立控制器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>
  1. 发布项目,运行测试:http://localhost:8080/springmvc03/upload.jsp
  2. 基于spring 3.0mvc 框架的文件上传实现

3、  进入项目发布后的目录,发现文件上传成功:

基于spring 3.0mvc 框架的文件上传实现

您可以通过点击 右下角 的按钮 来对文章内容作出评价, 也可以通过左下方的 关注按钮 来关注我的博客的最新动态。 

如果文章内容对您有帮助, 不要忘记点击右下角的 推荐按钮 来支持一下哦   

如果您对文章内容有任何疑问, 可以通过评论或发邮件的方式联系我: 2276292708@qq.com或加入JAVA技术交流群:306431857

如果需要转载,请注明出处,谢谢!!
上一篇:在用VMware虚拟机的时候,有时会发现打开虚拟机时提示“该虚拟机似乎正在使用中。如果该虚拟机未在使用,请按“获取所有权(T)”按钮获取它的所有权。否则,请按“取消(C)”按钮以防损坏。配置文件: D:\win10x64\Windows 10 x64.vmx。”这是由于虚拟机未正常关闭引起的,下面看看解决办法


下一篇:DataTable导出到Excel(.NET 4.0)