码迷,mamicode.com
首页 > 编程语言 > 详细

文件上传<springmvc>

时间:2015-09-23 15:06:45      阅读:268      评论:0      收藏:0      [点我收藏+]

标签:

使用commons-fileupload-1.3.1.jar和commons-io-2.4.jar

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">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<!-- springmvc前端控制器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- contextConfigLocation配置springmvc加载的配置文件(配置处理器映射器、适配器等等) -->
<!-- 如果不配置contextConfigLocation,默认加载的是/WEB-INF/servlet名称-serlvet.xml(springmvc-servlet.xml) -->

<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
</servlet>

<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!-- 第一种:*.action,访问以.action结尾 由DispatcherServlet进行解析 -->
<!-- 第二种:/,所以访问的地址都由DispatcherServlet进行解析,对于静态文件的解析需要配置不让DispatcherServlet进行解析 -->
<!-- 使用此种方式可以实现 RESTful风格的url -->
<!-- 第三种:/*,这样配置不对,使用这种配置,最终要转发到一个jsp页面时, -->
<!-- 仍然会由DispatcherServlet解析jsp地址,不能根据jsp页面找到handler,会报错。 -->

<url-pattern>*.action</url-pattern>
</servlet-mapping>

<filter>
<filter-name>SpringCharacterEncodingFilter</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>
</filter>
<filter-mapping>
<filter-name>SpringCharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

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

 

springmvc.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

 

<!-- 对于注解的Handler可以单个配置 实际开发中建议使用组件扫描 -->
<!-- <bean class="cn.demo.controller.ParamController" /> -->
<!-- 可以扫描controller、service、... 这里让扫描controller,指定controller的包 -->
<context:component-scan base-package="cn.demo.controller"></context:component-scan>

<!--spring3.1之后使用:注解映射器 -->
<!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> -->
<!--spring3.1之后使用:注解适配器 -->
<!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/> -->

<!-- 使用 mvc:annotation-driven代替上边注解映射器和注解适配器配置 -->
<!-- mvc:annotation-driven默认加载很多的参数绑定方法, -->
<!-- 比如json转换解析器就默认加载了,如果使用mvc:annotation-driven不用配置上边的RequestMappingHandlerMapping和RequestMappingHandlerAdapter -->
<!-- 实际开发时使用mvc:annotation-driven -->

<mvc:annotation-driven />


<!-- 视图解析器 -->
<!-- 解析jsp解析,默认使用jstl标签,classpath下的得有jstl的包 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 配置jsp路径的前缀 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 配置jsp路径的后缀 -->
<property name="suffix" value=".jsp" />
</bean>


<!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8" />
<!-- 指定所上传文件的总大小不能超过20000KB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->
<property name="maxUploadSize" value="20000000" />
</bean>

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

</beans>

 

controller:UserController

package cn.demo.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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 cn.demo.po.User;

/**
* SpringMVC中的文件上传
*
* @see 第一步:由于SpringMVC使用的是commons-fileupload实现,故将其组件引入项目中
* @see 这里用到的是commons-fileupload-1.3.1.jar和commons-io-2.4.jar
* @see 第二步:在springmvc.xml中配置MultipartResolver处理器。可在此加入对上传文件的属性限制
* @see 第三步:在Controller的方法中添加MultipartFile参数。该参数用于接收表单中file组件的内容
* @see 第四步:编写前台表单。注意enctype="multipart/form-data"以及<input type="file"
* name="****"/>不对字符编码。 在使用包含文件上传控件的表单时,必须使用该值。
* @author tinyseven
*/
@Controller
@RequestMapping("/user")
public class UserController {
private final static Map<String, User> users = new HashMap<String, User>();

// 模拟数据源,构造初始数据
public UserController() {
users.put("AAAA", new User("AAAA", "AAAA", "133569856", "AAAA@yeah.net"));
users.put("BBBB", new User("BBBB", "BBBB", "154699856", "BBBB@gulong.cn"));
users.put("CCCC", new User("CCCC", "CCCC", "154896965", "CCCC@manhuang.cc"));
users.put("DDDD", new User("DDDD", "DDDD", "177654646", "DDDD@xiyouji.zh"));
}

@RequestMapping("/list")
public String list(Model model, HttpServletRequest request) {
model.addAttribute("users", users);
// request.setAttribute("users", users);
return "user/list";
}

@RequestMapping(value = "/add", method = RequestMethod.GET)
public String addUser() {
return "user/add";
}

@RequestMapping(value = "/add", method = RequestMethod.POST)
public String addUser(User user, @RequestParam MultipartFile[] myfiles, HttpServletRequest request) throws IOException {
// 如果只是上传一个文件,则只需要MultipartFile类型接收文件即可,而且无需显式指定@RequestParam注解
// 如果想上传多个文件,那么这里就要用MultipartFile[]类型来接收文件,并且还要指定@RequestParam注解
// 并且上传多个文件时,前台表单中的所有<input
// type="file"/>的name都应该是myfiles,否则参数里的myfiles无法获取到所有上传的文件
for (MultipartFile myfile : myfiles) {
if (myfile.isEmpty()) {
System.out.println("未上传文件");
} else {
System.out.println("文件长度: " + myfile.getSize());
System.out.println("文件类型: " + myfile.getContentType());
System.out.println("文件名称: " + myfile.getName());
System.out.println("文件原名: " + myfile.getOriginalFilename());
System.out.println("========================================");
// 如果用的是Tomcat服务器,则文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\WEB-INF\\upload\\文件夹中
String realPath = request.getSession().getServletContext().getRealPath("/WEB-INF/upload");
// 这里不必处理IO流关闭的问题,因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉,我是看它的源码才知道的
FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath, myfile.getOriginalFilename()));
}
}
users.put(user.getUsername(), user);
return "redirect:/user/list.action";
}
}

 

jsp页面(WEB-INF/jsp/user/add.jsp)

add.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>adduser</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">
</head>
<body>
<form action="<%=request.getContextPath()%>/user/add.action" method="POST" enctype="multipart/form-data">
username: <input type="text" name="username"/><br/>
nickname: <input type="text" name="nickname"/><br/>
password: <input type="password" name="password"/><br/>
yourmail: <input type="text" name="email"/><br/>
yourfile: <input type="file" name="myfiles"/><br/>
yourfile: <input type="file" name="myfiles"/><br/>
yourfile: <input type="file" name="myfiles"/><br/>
<input type="submit" value="添加新用户"/>
</form>
</body>
</html>

jsp页面(WEB-INF/jsp/user/list.jsp)

list.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>list</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">
</head>
<body>
<c:forEach var="user" items="${users}">
<p>${user.value.username}----${user.value.nickname}----${user.value.password}----${user.value.email}</p>
<br />
</c:forEach>
<br />
<a href="<%=request.getContextPath()%>/user/add.action">继续添加用户</a>
</body>
</html>

文件上传<springmvc>

标签:

原文地址:http://www.cnblogs.com/jstarseven/p/4832117.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!