zoukankan      html  css  js  c++  java
  • Spring MVC文件上传和下载

    在Spring MVC中有两种实现上传文件的办法,第一种是Servlet3.0以下的版本通过commons-fileupload与commons-io完成的通用上传,第二种是Servlet3.0以上的版本的Spring内置标准上传,不需借助第3方组件。通用上传也兼容Servlet3.0以上的版本

    Servlet3.0以下的通过commons-fileupload上传

    1.添加上传依赖包

    一个是文件上传的jar包,一个是其所依赖的IO包。这两个jar包,均在Spring支持库的org.apache.commons中

    2.index.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%>">
        <style type="text/css">
           form{
           background-color:pink;
             width:500px;
           }
        </style>
        <title>单个文件上传</title>
      </head>
      
      <body>
        <form action="${pageContext.request.contextPath }/first.do" method="post" enctype="multipart/form-data">
        <h1>文件上传</h1>
                     文件:<input type="file" name="uploadFile"/><br/>
           <input type="submit" value="上传"/>
        </form>
      </body>
    </html>

    applicationContext.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:context="http://www.springframework.org/schema/context"
        xmlns:aop="http://www.springframework.org/schema/aop" 
        xmlns:tx="http://www.springframework.org/schema/tx" 
        xmlns:mvc="http://www.springframework.org/schema/mvc" 
         xsi:schemaLocation="
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
            ">
            
         <!-- 包扫描器 -->
         <context:component-scan base-package="cn.controller"></context:component-scan>
         
    </beans>

     书写处理器

    package cn.controller;
    
    import java.io.File;
    import javax.servlet.http.HttpSession;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.multipart.MultipartFile;
    
    /**
     * 
     * @author 景佩佩
     *
     */
    @Controller
    public class MyController{
         //处理器方法
        @RequestMapping(value="/first.do")
        //springmvc类型
        /**
         *   将文件对象保存到文件(图片)服务器上  Nugux
         *   
         * @param uploadFile  从页面上过来的真实文件对象
         * @return
         * @throws Exception
         */ 
        public String doFirst(MultipartFile uploadFile,HttpSession session) throws Exception{
                 //所有文件上传
                 //1.xxx:获取文件名作为保存到服务器的文件名称 1.jpg
                 String filename = uploadFile.getOriginalFilename();
    //2.前半部分路径,目录,将WebRoot下一个名称为images文件夹 转换成绝对路径 String leftPath = session.getServletContext().getRealPath("/images"); //3.进行路径拼接=前半部分路径+文件名称 File file=new File(leftPath,filename); //4.做保存 uploadFile.transferTo(file); return "welcome.jsp"; } }

     如果我们现在启动服务器,会报错

    在applicationContext.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:context="http://www.springframework.org/schema/context"
        xmlns:aop="http://www.springframework.org/schema/aop" 
        xmlns:tx="http://www.springframework.org/schema/tx" 
        xmlns:mvc="http://www.springframework.org/schema/mvc" 
         xsi:schemaLocation="
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
            ">
         
            <!-- 配置包扫描器-->
           <context:component-scan base-package="cn.controller"></context:component-scan>
           
           <!-- 文件上传解析器 -->
           <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
           
           </beans>

    但是启动的话还是会报错,因为我们没有配置注解驱动

    如果我们没有写解析器的ID的话,就会报另外的错

    文件上传大小设置

    如果超过限制的大小的话会报如下的错

    没有选择要上传的文件

    如果没有选择要上传的文件,可以通过如下判断代码回到错误页

    限制上传的文件

     

    如果我们上传的文件中有乱码的问题,我们可以使用以下两种方式

    1)

     2)

    <filter>
        <filter-name>characterEncoding</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>forceEncoding</param-name>
          <param-value>true</param-value>
        </init-param>
      </filter>
      <filter-mapping>
        <filter-name>characterEncoding</filter-name>
        <url-pattern>/*</url-pattern>
      </filter-mapping

    多文件上传

    首先index.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%>">
        <style type="text/css">
           form{
           background-color:pink;
             width:500px;
           }
        </style>
        <title></title>
      </head>
      
      <body>
        <form action="${pageContext.request.contextPath }/first.do" method="post" enctype="multipart/form-data">
        <h1>文件上传</h1>
                     文件1:<input type="file" name="uploadFile"/><br/>
                         文件2:<input type="file" name="uploadFile"/><br/>
                             文件3:<input type="file" name="uploadFile"/><br/>
           <input type="submit" value="上传"/>
        </form>
      </body>
    </html>

    2.applicationContext.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:context="http://www.springframework.org/schema/context"
        xmlns:aop="http://www.springframework.org/schema/aop" 
        xmlns:tx="http://www.springframework.org/schema/tx" 
        xmlns:mvc="http://www.springframework.org/schema/mvc" 
         xsi:schemaLocation="
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
            ">
            
         <!-- 包扫描器 -->
         <context:component-scan base-package="cn.controller"></context:component-scan>
         
         <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
             <property name="maxUploadSize" value="50000000"></property>
             <property name="maxUploadSizePerFile" value="5000000"></property> 
              <property name="defaultEncoding" value="utf-8"></property> 
         </bean>
         <!--mvc注解驱动 包括:创建MultipartFile 实例 -->
         <mvc:annotation-driven/>
         </beans>

    3.书写处理器

    package cn.controller;
    
    import java.io.File;
    import javax.servlet.http.HttpSession;
    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;
    
    /**
     * 
     * @author 景佩佩
     *
     */
    @Controller
    public class MyController{
         //处理器方法
        @RequestMapping(value="/first.do")
        //springmvc类型
        /**
         *   将文件对象保存到文件(图片)服务器上  Nugux
         *   
         * @param uploadFile  从页面上过来的真实文件对象
         * @return
         * @throws Exception
         */ 
        public String doFirst(@RequestParam MultipartFile[] uploadFile,HttpSession session) throws Exception{
            for (MultipartFile item : uploadFile) {
                if (item.getSize()>0) {
                    
                    //通过文件后缀名判定只能让用户上传 .jpg .gif .png
                    //所有文件上传
                    //1.xxx:获取文件名作为保存到服务器的文件名称 1.jpg
                    String filename = item.getOriginalFilename();
                    
                    if (filename.endsWith("jpg")||filename.endsWith("gif")||filename.endsWith("png")) {
                        //2.前半部分路径,目录,将WebRoot下一个名称为images文件夹  转换成绝对路径
                        String leftPath = session.getServletContext().getRealPath("/images");
    
                        //3.进行路径拼接=前半部分路径+文件名称
                        File file=new File(leftPath,filename);
                        item.transferTo(file);
        
                    } 
                }else {
                    return "error.jsp";
                }
            }
            
            return "welcome.jsp";
        }
    
    }

     提醒:在处理器方法中一定要对参数进行校对使用注解@RequestParam校正参数

    要不然会报如下错误

    之后就可以实现文件上传

    文件下载

    index.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%>">
        <style type="text/css">
           form{
           background-color:pink;
             width:500px;
           }
        </style>
        <title>单个文件上传</title>
      </head>
      
      <body>
         <form action="${pageContext.request.contextPath }/download.do" method="post" enctype="multipart/form-data">
        <h1>文件下载</h1>
             <a href="${pageContext.request.contextPath }/download.do?1.jpg">下载</a>
        </form>
      </body>
    </html>

     applicationContext.xml不用配置(与之前上传的一样)

    处理器MyController

     

  • 相关阅读:
    java中math类
    java中的值传递和引用传递(转)
    eclipse 字体和配色修改
    JAR WAR EAR包的区别
    java中基本类型
    tomcat 7.0 配置详解
    或许你需要一些可操作性更强的实践
    Assembly.CreateInstance()与Activator.CreateInstanc
    OOD沉思录2 类和对象的关系包含关系
    C#的插件开发
  • 原文地址:https://www.cnblogs.com/jingpeipei/p/6270407.html
Copyright © 2011-2022 走看看