您好,欢迎访问一九零五行业门户网

SpringMVC中的文件上传代码实例详解

这是用的是springmvc-3.1.1、commons-fileupload-1.2.2和io-2.0.1
首先是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"> <servlet> <servlet-name>upload</servlet-name> <servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>upload</servlet-name> <url-pattern>/</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>/web-inf/jsp/user/add.jsp</welcome-file> </welcome-file-list> </web-app>
接下来是springmvc的配置文件upload-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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="com.jadyer"/> <bean class="org.springframework.web.servlet.view.internalresourceviewresolver"> <property name="prefix" value="/web-inf/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"/> <!-- 指定所上传文件的总大小不能超过200kb。注意maxuploadsize属性的限制不是针对单个文件,而是所有文件的容量之和 --> <property name="maxuploadsize" value="200000"/> </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>
下面是用于上传的表单页面//web-inf//jsp//user//add.jsp
<%@ page language="java" pageencoding="utf-8"%> <form action="<%=request.getcontextpath()%>/user/add" 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>
下面是上传成功后打印用户信息的页面//web-inf//jsp//user//list.jsp
<%@ page language="java" pageencoding="utf-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <c:foreach items="${users}" var="user"> ${user.value.username}----${user.value.nickname}----${user.value.password}----${user.value.email} <a href="<%=request.getcontextpath()%>/user/${user.value.username}">查看</a> <a href="<%=request.getcontextpath()%>/user/${user.value.username}/update">编辑</a> <a href="<%=request.getcontextpath()%>/user/${user.value.username}/delete">删除</a> <br/> </c:foreach> <br/> <a href="<%=request.getcontextpath()%>/user/add">继续添加用户</a>
下面是上传文件内容过大时的提示页面//web-inf//jsp//error_fileupload.jsp
<%@ page language="java" pageencoding="utf-8"%> <h1>文件过大,请重新选择</h1>
接下来是用到的实体类user.java
package com.jadyer.model; /** * user * @author 宏宇 * @create may 12, 2012 1:24:43 am */ public class user { private string username; private string nickname; private string password; private string email; /*==四个属性的getter()、setter()略==*/ public user() {} public user(string username, string nickname, string password, string email) { this.username = username; this.nickname = nickname; this.password = password; this.email = email; } }
最后是核心的usercontroller.java
package com.jadyer.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 com.jadyer.model.user; /** * springmvc中的文件上传 * @see 第一步:由于springmvc使用的是commons-fileupload实现,故将其组件引入项目中 * @see 这里用到的是commons-fileupload-1.2.2.jar和commons-io-2.0.1.jar * @see 第二步:在####-servlet.xml中配置multipartresolver处理器。可在此加入对上传文件的属性限制 * @see 第三步:在controller的方法中添加multipartfile参数。该参数用于接收表单中file组件的内容 * @see 第四步:编写前台表单。注意enctype="multipart/form-data"以及<input type="file" name="****"/> * @author 宏宇 * @create may 12, 2012 1:26:21 am */ @controller @requestmapping("/user") public class usercontroller { private final static map<string,user> users = new hashmap<string,user>(); //模拟数据源,构造初始数据 public usercontroller(){ users.put("张起灵", new user("张起灵", "闷油瓶", "02200059", "menyouping@yeah.net")); users.put("李寻欢", new user("李寻欢", "李探花", "08866659", "lixunhuan@gulong.cn")); users.put("拓拔野", new user("拓拔野", "搜神记", "05577759", "tuobaye@manhuang.cc")); users.put("孙悟空", new user("孙悟空", "美猴王", "03311159", "sunhouzi@xiyouji.zh")); } @requestmapping("/list") public string list(model model){ model.addattribute("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"; } }
补充:记得建立这个目录,用于存放上传的文件,即//web-inf//upload//
以上就是springmvc中的文件上传代码实例详解的内容。
其它类似信息

推荐信息