使用spring MVC框架进行文件上传

http://ispring.javaeye.com/blog/156469

在 Spring 中, MultipartResolver 主要用来处理文件上传,它支持 Commons FileUpload (http://jakarta.apache.org/commons/fileupload) 和 COS FileUpload (http://www.servlets.com/cos)。
缺省,Spring是没有multipart处理,因为一些开发者想要自己处理它们。如果你想使用Spring的multipart,需要在web应用的上下文中添加multipart解析器。这样,每个请求就会被检查是否包含multipart。然而,如果请求中包含multipart,你的上下文中定义的 MultipartResolver就会解析它。这样,你请求中的multipart属性就会象其它属性一样被处理。
主要配置如下:
Java代码 复制代码
  1. <bean id="multipartResolver"     class="org.springframework.web.multipart.commons.CommonsMultipartResolver">   
  2. <!-- 该属性用来配置可上传文件的最大 byte 数 -->   
  3. <property name="maximumFileSize"><value>100000</value></property>   
  4. </bean>  
<bean id="multipartResolver"     class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 该属性用来配置可上传文件的最大 byte 数 -->
<property name="maximumFileSize"><value>100000</value></property>
</bean>

该 Bean 还有其它的属性如 defaultEncoding, maxInMemorySize, servletContext, uploadTempDir 一般默认就可以了。
其它的配置和普通的没有什么区别,当然在上传的表单中必须指定其 enctype 为 mulitpart/form-data ,如:
Java代码 复制代码
  1.  <form method="post" action="upload.html" enctype="multipart/form-data">   
  2.     <input type="file" name="paper" />   
  3.     <input type="text" name="name"/>   
  4.     <input type="submit"/>   
  5. </form>  
 <form method="post" action="upload.html" enctype="multipart/form-data">
    <input type="file" name="paper" />
    <input type="text" name="name"/>
    <input type="submit"/>
</form>

最后一点就是项目中必须有 commons-io.jar , commons-fileupload.jar 包的支持。

 

 

http://blog.csdn.net/sleepbird/archive/2007/04/16/1566090.aspx

使用spring MVC框架进行文件上传,步骤如下:

1:配置web.xml文件。定义DispatcherServlet,DispatcherServlet处理的请求(.htm)也在同一个web.xml文件里使用url-mapping定义映射。

 <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>*.htm</url-pattern>
 </servlet-mapping>
2:定义upload-servlet.xml文件。
<bean id="multipartResolver"
       class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- set the max upload size100MB -->
        <property name="maxUploadSize">
        <value>104857600</value>
    </property>
    <property name="maxInMemorySize">
        <value>4096</value>
    </property>
   </bean>
 <bean id="urlMapping"
  class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">       
 <property name="mappings">           
  <props>               
  <prop key="/upload.htm">uploadController</prop>           
  </props>       
 </property>   
 </bean>
     <bean id="uploadController" class="FileUploadController">
      <property name="commandClass"><value>FileUploadBean</value></property>
      <property name="uploadDir"><value>E:/</value></property>
      <property name="formView"><value>fail</value></property>
  <property name="successView"><value>confirmation</value></property>
</bean>  
3:定义控制类,commandClass及方法。控制类中最重要的方法是initBinder()它给spring注册了一个编辑器对
request中的multipart实体进行处理,如果没有这个方法,上传将不能进行。
<--------------------------控制类------------------->
public class FileUploadController extends SimpleFormController {
    private static Log log =
        LogFactory.getLog(FileUploadController.class);
    private String uploadDir;//上传文件路径

    protected ModelAndView onSubmit(HttpServletRequest request,
            HttpServletResponse response, Object cmd, BindException errors)
            throws Exception {

            FileUploadBean bean = (FileUploadBean) cmd;
            byte[] bytes = bean.getFile();
          
            //cast to multipart file so we can get additional information
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");

            String uploadDir = this.getUploadDir();

            File dirPath = new File(uploadDir);
            if (!dirPath.exists()) {
                dirPath.mkdirs();
            }
            String sep = System.getProperty("file.separator");
            if (log.isDebugEnabled()) {
                log.debug("uploading to: " + uploadDir + sep +
                file.getOriginalFilename());
                }
            File uploadedFile = new File(uploadDir + sep
                    + file.getOriginalFilename());
            FileCopyUtils.copy(bytes, uploadedFile);
            System.out.println("********************************");
            System.out.println(uploadedFile.getAbsolutePath());
            System.out.println(bytes.length);
            System.out.println("********************************");
           
     
        return new ModelAndView(getSuccessView() + ".jsp");
    }

    protected void initBinder(HttpServletRequest request,
            ServletRequestDataBinder binder) throws ServletException {
        binder.registerCustomEditor(byte[].class,
                new ByteArrayMultipartFileEditor());
    }
    public void setUploadDir(String uploadDir){
        this.uploadDir = uploadDir;
    }
    public String getUploadDir(){
        return this.uploadDir;
    }
}
<--------------------------控制类------------------------->
<---------------------定义commandClass-------------------->
public class FileUploadBean {

    private byte[] file;

    public void setFile(byte[] file) {
        this.file = file;
    }

    public byte[] getFile() {
        return file;
    }

}
<---------------------定义commandClass-------------------->
4:定义一个form表单index.jsp
<form method="post" action="upload.htm" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit"/>
5:定义confirmation.jsp及fail.jsp
confirmation.jsp如下:
<%@ page contentType="text/html; charset=GBK" %>
<html>
<head>
<title>
successView
</title>
</head>
<body bgcolor="#ffffff">
<h1>
Upload Successful
</h1>
</body>
</html>

fail.jsp如下:
<html>
<head>
<title>Upload a file please</title>
</head>
<body>
<h1>no file,Please upload a file</h1>
<form method="post" action="uploadfile.htm" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit"/>
</form>
</body>
</html>
6:运行tomcat。
预览 ie里面:http://localhost/springmvc/index.jsp
注:
a:文件目录为tomcat-HOME/webapps/springmvc/
.jsp文件都放在根目录下,.class文件放在/WEB-INF/classes/中

其他文件放在/WEB-INF/里面。
b:如果连上面的你都有疑问,那还是去看看spring的基础知识吧。

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/sleepbird/archive/2007/04/16/1566090.aspx

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值