springMVC上傳文件

一、文件上傳的必要前提

  1. form表單的enctype取值必須是:multipart/form-data (默認值是:application/x-www-form-urlencoded) enctype:是表單請求正文的類型
  2. method屬性取值必須是Post
  3. 提供一個文件選擇域

二、文件上傳環境搭建

在這裏插入圖片描述
2.1、在pom.xml中導入相關依賴

<properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <maven.compiler.source>1.8</maven.compiler.source>
  <maven.compiler.target>1.8</maven.compiler.target>
  <!--spring版本鎖定-->
  <spring.version>5.0.2.RELEASE</spring.version>
</properties>

<dependencies>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>org.apache.tomcat</groupId>
    <artifactId>tomcat-api</artifactId>
    <version>7.0.47</version>
  </dependency>
  <dependency>
    <groupId>org.apache.tomcat</groupId>
    <artifactId>tomcat-jasper-el</artifactId>
    <version>7.0.47</version>
  </dependency>
  
  <!--導入文件上傳的依賴jar包-->
  <dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
  </dependency>
  <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.4</version>
    </dependency>
</dependencies>

2.2、在web.xml中配置SpringMVC核心控制器

<web-app 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_3_0.xsd"
         version="3.0">

  <!--編碼過濾器-->
  <filter>
    <filter-name>encoding</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>encoding</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <!--配置SpringMVC核心控制器-->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 配置Servlet的初始化參數,讀取springmvc的配置文件,創建spring容器 -->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <!-- 配置servlet啓動時加載對象 -->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <!--配置springmvc過請求過濾器,/表示所有請求都經過springmvc處理-->
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

2.3、配置SpringMVC核心配置文件springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       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.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 配置創建spring容器要掃描的包 -->
    <context:component-scan base-package="com.itheima"></context:component-scan>

    <!-- 配置視圖解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <!--設置靜態資源不過濾-->
    <mvc:resources mapping="/css/**" location="/css/**"></mvc:resources>
    <mvc:resources location="/images/" mapping="/images/**" />
    <mvc:resources location="/js/" mapping="/js/**" />

    <!--
        配置文件上傳解析器
        ID的值是固定的  multipartResolver
        class的值也是固定的
    -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--設置上傳文件的最大尺寸爲10MB-->
        <property name="maxUploadSize" value="10485760"></property>
    </bean>
    
    <!--SpringMVC註解驅動-->
    <mvc:annotation-driven></mvc:annotation-driven>
</beans>

2.4、 編寫文件上傳頁面upload.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>文件上傳</title>
</head>
<body>
    <h1>springMVC方式文件上傳</h1>
    <form action="${pageContext.request.contextPath}/file/upload2" method="post" enctype="multipart/form-data">

        文件上傳:<input type="file" name="file">
        <input type="submit" value="開始上傳" >
    </form>

    <form action="${pageContext.request.contextPath}/file/fileupload2" method="post" enctype="multipart/form-data">

        文件上傳:<input type="file" name="upload">
        <input type="submit" value="開始上傳" enctype="multipart/form-data">
    </form>
</body>
</html>

還有成功的界面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>成功的界面</title>
</head>
<body>
<h2>文件上傳成功</h2>
</body>
</html>

2.5、編寫控制層代碼FileController

@Controller
@RequestMapping("/file")
public class FileController {
	@RequestMapping(value = "/fileupload2")
	    public String fileuoload2(HttpServletRequest request, MultipartFile upload) throws Exception {
	        System.out.println("springmvc文件上傳...");
	
	        // 使用fileupload組件完成文件上傳
	        // 上傳的位置
	        //String path = request.getSession().getServletContext().getRealPath("/uploads/");
	        String path="C:\\Users\\xioayue\\Desktop\\aa\\";
	        // 判斷,該路徑是否存在
	        File file = new File(path);
	        if(!file.exists()){
	            // 創建該文件夾
	            file.mkdirs();
	        }
	
	        // 說明上傳文件項
	        // 獲取上傳文件的名稱
	        String filename = upload.getOriginalFilename();
	        // 把文件的名稱設置唯一值,uuid
	        String uuid = UUID.randomUUID().toString().replace("-", "");
	        filename = uuid+"_"+filename;
	        // 完成文件上傳
	        upload.transferTo(new File(path,filename));
	
	        return "success";
	    }
    }

三、springMVC實現多文件上傳

3.1、編寫文件上傳頁面upload.jsp

<h1>SpringMVC方式多選文件上傳</h1>
<form action="${pageContext.request.contextPath }/file/multi" method="post" enctype="multipart/form-data" >
    文件描述:<input type="text" name="desc"><br>
    文件上傳:<input type="file" name="files"><br>
    文件上傳:<input type="file" name="files"><br>
    <input type="submit" value="開始上傳">
</form>

3.2、編寫服務器web層代碼FileController

@RequestMapping(path="/multi",method = RequestMethod.POST)
public String upload3(MultipartFile[] files) throws Exception {

    //1. 獲取一個文件輸出的磁盤路徑
    String path = "C:\\Users\\Administrator\\Desktop\\upload";
    File dir = new File(path);
    if(!dir.exists()){
        dir.mkdir();
    }

    //遍歷文件集合
    for (MultipartFile file : files) {
        //2. 獲取文件名稱
        String filename = file.getOriginalFilename();
        //3. 獲取文件內容
        InputStream is = file.getInputStream();//獲取文件內容

        //4. 創建輸出流
        OutputStream os = new FileOutputStream(path + "/" + filename);

        //5. 將文件內容通過輸出流寫到磁盤文件中
        int i = 0;
        byte[] bys = new byte[1024];

        while ((i = is.read()) != -1) {
            os.write(bys, 0, i);
        }
        os.close();
    }

    return "success";
}

四、傳統的文件上傳

4.1、編寫文件上傳頁面upload.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上傳表單</title>
</head>
<body>
    <form action="${pageContext.request.contextPath }/UploadServlet" method="post" enctype="multipart/form-data" >
        文件描述:<input type="text" name="fileDescribe"><br>
        文件上傳:<input type="file" name="file"><br>
        <input type="submit" value="開始上傳">
    </form>
</body>
</html>

4.2、編寫文件上傳的控制層方法FileController

@Controller
@RequestMapping("/file")
public class FileController {

  /**
   * 傳統方式文件上傳
   * @param request  請求對象 包含文件上傳信息
   * @param response
   * @throws Exception
   */
  @RequestMapping(path="/upload",method = RequestMethod.POST)
  public void upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
      //1. 創建磁盤文件工廠
      DiskFileItemFactory factory = new DiskFileItemFactory();
      //2. 創建核心的解析類
      ServletFileUpload upload = new ServletFileUpload(factory);

      //3. 解析請求對象,獲取到各個部分
      List<FileItem> fileItems = upload.parseRequest(request);

      //4. 獲取一個文件輸出的磁盤路徑
      String path = "C:\\Users\\Administrator\\Desktop\\upload";
      File dir = new File(path);
      if(!dir.exists()){
          dir.mkdir();
      }

      //5. 遍歷表單的各項
      for (FileItem fileItem : fileItems) {

          //6. 判斷是普通項還是文件上傳項
          if (fileItem.isFormField()) { // 普通項
              String name = fileItem.getFieldName(); //獲取普通項name屬性的值
              String value = fileItem.getString();   //獲取普通項value屬性的值
              System.out.println(name + " " + value);
          } else { //文件上傳項
              String name = fileItem.getName();//獲取文件名稱  a.txt
              InputStream is = fileItem.getInputStream();//獲取文件內容

              //創建輸出流
              OutputStream os = new FileOutputStream(path + "/" + name);

              // 將文件內容通過輸出流寫到磁盤文件中
              int i = 0;
              byte[] bys = new byte[1024];

              while ((i = is.read()) != -1) {
                  os.write(bys, 0, i);
              }
              os.close();
              is.close();
          }
      }
  }
}

4.3、總結

  1. 創建磁盤文件工廠DiskFileItemFactory factory = new DiskFileItemFactory();
  2. 創建核心的解析類 ServletFileUpload upload = new ServletFileUpload(factory);
  3. 解析文件上傳的請求,獲取文件上傳的各個部分 List fileItems = upload.parseRequest(request);
  4. 遍歷文件上傳的各個部分,判斷是一個文件上傳項還是一個普通的表單項
    如果是一個文件上傳項,獲取文件名稱和文件內容,創建一個輸出流將文件寫到磁盤上
    如果是一個普通的表單項,獲取name和value就可以了
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章