【Spring】(17)Spring MVC 上傳下載

一、文件上傳下載

SpringMVC上下文默認中沒有裝配MultipartResolver,因此默認情況不能處理文件上傳和下載。如果想使用Spring的文件上傳功能,則需要在上下文(配置文件)中配置MultipartResolver。

該篇實現了文件的上傳下載,主要學習一個思路。

1.項目結構

在這裏插入圖片描述

2.配置文件

pom.xml依賴

需要添加一個文件上傳的jar,commons-fileupload,不添加會報錯。

順便把servlet的api(在項目依賴的library中加入tomcat也可以)也添加了。這樣就不用在項目library中中添加tomcat了。

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.5.RELEASE</version>
        </dependency>
        <!-- 文件上傳 -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.4</version>
        </dependency>
        <!-- servlet的api(在項目依賴的library中加入tomcat也可以) -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!--配置DispatcherServlet-->
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--關聯一個SpringMVC的配置文件-->
        <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>DispatcherServlet</servlet-name>
        <!--  "/"匹配所有的請求不包括.jsp。"/*"匹配所有的請求包括.jsp -->
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- 配置Spring MVC編碼過濾器(解決亂碼) -->
    <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>
    </filter>
    <filter-mapping>
        <filter-name>encoding</filter-name>
        <!--  "/"匹配所有的請求不包括.jsp。"/*"匹配所有的請求包括.jsp -->
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

springmvc-servlet.xml配置文件。

添加了文件上傳。注意:文件上傳bean的id一定要是multipartResolver

<?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
        https://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 掃描包,讓指定包下的註解生效,有IoC容器統一管理 -->
    <context:component-scan base-package="com.shengjava.web"/>
    <!--開啓註解掃描-->
    <mvc:annotation-driven/>
    <!--在web開發中,我們一般存在靜態資源css,js,img。。。-->
    <mvc:default-servlet-handler/>

    <!--視圖解析器-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--前綴-->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!--後綴-->
        <property name="suffix" value=".jsp"/>
    </bean>

    <!-- 文件上傳 -->
    <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="1024"/>
    </bean>
</beans>

3.jsp頁面

index.jsp文件上傳頁面

注意:表單的method屬性需要設置爲"post",並且enctype屬性要設置爲"multipart/form-data"。

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="file">
        <input type="submit" value="提交">
    </form>
    <a href="/download">文件下載</a>
</body>
</html>

4.測試

編寫測試類,主要是文件上傳和下載

CommonsMultipartFile 類是Spring的,用於文件上傳。

@Controller
public class FileController {
    /**
     * 上傳文件頁面
     */
    @GetMapping("/")
    public String upload() {
        return "index";
    }

    /**
     * 使用spring的文件上傳方法(推薦)
     */
    @ResponseBody
    @PostMapping("/upload")
    public String upload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
        //設置上傳路徑
        String path = request.getServletContext().getRealPath("/upload");
        //如果路徑不存在,創建一個
        File realPath = new File(path);
        if (!realPath.exists()) {
            realPath.mkdir();
        }
        //通過CommonsMultipartFile的方法直接寫文件(注意這個時候)
        file.transferTo(new File(realPath, file.getOriginalFilename()));
        return "success";
    }

    /**
     * 自己寫文件上傳
     */
    @ResponseBody
    @PostMapping("/uploadIo")
    public String upload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
        //獲取文件名
        String uploadFileName = file.getOriginalFilename();
        //如果文件名爲空,直接回到首頁!
        if (uploadFileName == null) {
            return "redirect:/";
        }
        //設置上傳路徑
        String path = request.getServletContext().getRealPath("/upload");
        //如果路徑不存在,創建一個
        File realPath = new File(path);
        if (!realPath.exists()) {
            realPath.mkdir();
        }
        //文件輸入流
        InputStream is = file.getInputStream();
        //文件輸出流    輸出到上傳路徑下的與該文件名相同的文件中
        OutputStream os = new FileOutputStream(new File(realPath, uploadFileName));
        //讀取寫出
        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = is.read(bytes)) != -1) {
            os.write(bytes, 0, len);
            os.flush();
        }
        os.close();
        is.close();
        return "success";
    }

    /**
     * 下載文件
     */
    @ResponseBody
    @GetMapping("/download")
    public String fileDownLoad(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //要下載的圖片地址
        String path = request.getServletContext().getRealPath("/upload");
        String fileName = "springboot.jpg";
        //設置頁面不緩存,清空buffer
        response.reset();
        //字符編碼
        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);
        //文件輸入流
        InputStream is = new FileInputStream(file);
        //文件輸入流
        OutputStream os = response.getOutputStream();
        int len = 0;
        byte[] bytes = new byte[1024];
        while ((len = is.read(bytes)) != -1) {
            os.write(bytes, 0, len);
            os.flush();
        }
        is.close();
        os.close();
        return "";
    }
}

訪問接口"/“可以進入下載頁面,選中文件進行上傳,上傳成功會返回"success”。

然後返回接口"/",可以點擊文件下載。可以下載我們在fileDownLoad()方法中設置的文件地址。

參考自:SpringMVC學習(七)


相關

我的該分類的其他相關文章,請點擊:【Spring + Spring MVC + MyBatis】文章目錄

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