Java框架之SpringMVC(五)文件上傳和下載

借鑑博客:https://www.cnblogs.com/hellokuangshen/p/11289940.html

文件上傳和下載

springMVC 可以很好的支持文件上傳,但是SpringMVC上下文中默認沒有裝配MultipartResolver,因此默認情況下其不能處理文件上傳工作。如果想使用Spring的文件上傳功能,則需要在上下文中配置MultipartResolver。

準備工作

前端表單要求:爲了能上傳文件,必須將表單的method設置爲POST,並將enctype設置爲multipart/form-data。只有在這樣的情況下,瀏覽器纔會把用戶選擇的文件以二進制數據發送給服務器;

對錶單中的 enctype 屬性做個詳細的說明:

  • application/x-www=form-urlencoded:默認方式,只處理表單域中的 value 屬性值,採用這種編碼方式的表單會將表單域中的值處理成 URL 編碼方式。
  • multipart/form-data:這種編碼方式會以二進制流的方式來處理表單數據,這種編碼方式會把文件域指定文件的內容也封裝到請求參數中,不會對字符編碼。
  • text/plain:除了把空格轉換爲 “+” 號外,其他字符都不做編碼處理,這種方式適用直接通過表單發送郵件。
<form action="" enctype="multipart/form-data" method="post">
    <input type="file" name="file"/>
    <input type="submit">
</form>

一旦設置了enctype爲multipart/form-data,瀏覽器即會採用二進制流的方式來處理表單數據,而對於文件上傳的處理則涉及在服務器端解析原始的HTTP響應。

Spring MVC爲文件上傳提供了直接的支持,這種支持是用即插即用的MultipartResolver實現的。Spring MVC使用Apache Commons FileUpload技術實現了一個MultipartResolver實現類:CommonsMultipartResolver。因此,SpringMVC的文件上傳還需要依賴Apache Commons FileUpload的組件。

在springmvc-servlet.xml進行配置文件如下:

注意!!!這個bena的id必須爲:multipartResolver , 否則上傳文件會報400的錯誤!在這裏栽過坑,教訓!

<!--文件上傳配置-->
    <bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 請求的編碼格式,必須和jSP的pageEncoding屬性一致,以便正確讀取表單的內容,默認爲ISO-8859-1 -->
        <property name="defaultEncoding" value="utf-8"/>
        <!-- 上傳文件大小上限,單位爲字節(10485760=10M) -->
        <property name="maxUploadSize" value="10485760"/>
        <property name="maxInMemorySize" value="40960"/>
    </bean>

除此之外,我們還需要導入文件上傳的jar包,commons-fileupload , Maven會自動幫我們導入他的依賴包 commons-io包;

<!--文件上傳-->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.3</version>
    </dependency>

我們會使用它的實現類 CommonsMultipartFile , 常用方法

String getOriginalFilename():獲取上傳文件的原名
InputStream getInputStream():獲取文件流
void transferTo(File dest):將上傳文件保存到一個目錄文件中
我們去實際測試一下

springMVC實現文件上傳

方式一:採用流的方式上傳文件

controller文件:

//文件上傳:流
    @RequestMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
        //1.獲得文件名
        String filename = file.getOriginalFilename();
        if ("".equals(filename)){
            return "文件不存在";
        }
        //2.上傳文件保存路徑
        String path = request.getServletContext().getRealPath("/upload");
        File realPath = new File(path);
        if (!realPath.exists()){
            realPath.mkdir();
        }
        //3.上傳文件
        InputStream is = file.getInputStream();
        FileOutputStream os = new FileOutputStream(new File(realPath, filename));

        int len = 0;
        byte[] buffer =  new byte[1024];

        while ((len=is.read(buffer))!=-1){
            os.write(buffer,0,len);
            os.flush();
        }

        //4.關閉流
        os.close();
        is.close();
        return "上傳完畢";
    }

前端頁面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>

<form enctype="multipart/form-data" method="post" action="${pageContext.request.contextPath}/upload2">
    <input type="file" name="file">
    <<input type="submit">
</form>

</body>
</html>

結果輸出:
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

採用file.Transto 來上傳

controller:

文件上傳:CommonsMultipartFile
    @RequestMapping(value = "/upload2")
    @ResponseBody
    public String upload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {

        //上傳文件保存路徑
        String path = request.getServletContext().getRealPath("/upload");
        File realPath = new File(path);
        if (!realPath.exists()){
            realPath.mkdir();
        }

        //transferTo:將文件寫入到磁盤,參數就是一個文件
        file.transferTo(new File(realPath+"/"+file.getOriginalFilename()));

        return "上傳完畢";
    }

其他文件配置不變

完整項目實現

項目結構:
在這裏插入圖片描述

pom.xml文件配置:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>SpringMVC</artifactId>
        <groupId>com.kuang</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>demo07_springmvc_file_intercepter</artifactId>
    <packaging>war</packaging>

    <name>demo07_springmvc_file_intercepter Maven Webapp</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <!--文件上傳和下載的包commons-fileupload,依賴於commons-io-->
        <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
        </dependency>

    </dependencies>

    <build>
        <finalName>demo07_springmvc_file_intercepter</finalName>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
            <plugins>
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.1.0</version>
                </plugin>
                <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.22.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>2.5.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.8.2</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>


web.xml文件配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
         http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         id="WebApp_ID" version="3.0">

  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>


  <!--配置過濾器-->
  <filter>
    <filter-name>myFilter</filter-name>
    <!--<filter-class>com.kuang.filter.GenericEncodingFilter</filter-class>-->
    <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>
  <!--/*  包括.jsp-->
  <filter-mapping>
    <filter-name>myFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>


</web-app>

springmvc-servlet.xml文件配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
         http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         id="WebApp_ID" version="3.0">

  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>


  <!--配置過濾器-->
  <filter>
    <filter-name>myFilter</filter-name>
    <!--<filter-class>com.kuang.filter.GenericEncodingFilter</filter-class>-->
    <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>
  <!--/*  包括.jsp-->
  <filter-mapping>
    <filter-name>myFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>


</web-app>

fileUploadController文件:

package com.kuang.controller;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import sun.security.util.Length;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;

@Controller
public class FileUploadController {

    //文件上傳:流
    @RequestMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
        //1.獲得文件名
        String filename = file.getOriginalFilename();
        if ("".equals(filename)){
            return "文件不存在";
        }
        //2.上傳文件保存路徑
        String path = request.getServletContext().getRealPath("/upload");
        File realPath = new File(path);
        if (!realPath.exists()){
            realPath.mkdir();
        }
        //3.上傳文件
        InputStream is = file.getInputStream();
        FileOutputStream os = new FileOutputStream(new File(realPath, filename));

        int len = 0;
        byte[] buffer =  new byte[1024];

        while ((len=is.read(buffer))!=-1){
            os.write(buffer,0,len);
            os.flush();
        }

        //4.關閉流
        os.close();
        is.close();
        return "上傳完畢";
    }

    //文件上傳:CommonsMultipartFile
    @RequestMapping(value = "/upload2")
    @ResponseBody
    public String upload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {

        //上傳文件保存路徑
        String path = request.getServletContext().getRealPath("/upload");
        File realPath = new File(path);
        if (!realPath.exists()){
            realPath.mkdir();
        }

        //transferTo:將文件寫入到磁盤,參數就是一個文件
        file.transferTo(new File(realPath+"/"+file.getOriginalFilename()));

        return "上傳完畢";
    }

}

文件下載實現

文件下載步驟:
設置 response 響應頭
讀取文件 – InputStream
寫出文件 – OutputStream
執行操作
關閉流 (先開後關)

代碼實現:

@RequestMapping(value="/download")
    public String downloads(HttpServletResponse response) throws Exception{
        //要下載的圖片地址
        String    path = "C:/Users/Administrator/Desktop/";
        String  fileName = "1.png";

        //1、設置response 響應頭
        response.reset(); //設置頁面不緩存,清空buffer
        response.setCharacterEncoding("UTF-8"); //字符編碼
        response.setContentType("multipart/form-data"); //二進制傳輸數據
        //設置響應頭
        response.setHeader("Content-Disposition",
                "attachment;fileName="+URLEncoder.encode(fileName, "UTF-8"));

        File file = new File(path,fileName);
        //2、 讀取文件--輸入流
        InputStream input=new FileInputStream(file);
        //3、 寫出文件--輸出流
        OutputStream out = response.getOutputStream();

        byte[] buff =new byte[1024];
        int index=0;
        //4、執行 寫出操作
        while((index= input.read(buff))!= -1){
            out.write(buff, 0, index);
            out.flush();
        }
        out.close();
        input.close();
        return null;
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章