1. 程式人生 > >Spring MVC 上傳檔案(upload files)

Spring MVC 上傳檔案(upload files)

上傳功能是一個web應用很常用的一個功能,比如在一些社交網站上傳些圖片、視訊等。本篇文章主要研究了spring mvc是如何實現檔案上傳功能的,在具體講解spring mvc如何實現處理檔案上傳之前,必須弄明白與檔案上傳相關的multipart請求

一、關於multipart 請求

我們傳統的表單提交的一般都是文字型別的資料,比如我們的登錄檔單,當提交表單時,表單中的“屬性-值”對會被拼接成一個字串:

firstName=Charles&lastName=Xavier&email=professorx%40xmen.org
&username=professorx&password=letmein01

這種處理方式很簡單也很有效,但是對於圖片、視訊等二進位制資料就不能這麼處理了,這裡就要用到multipart表單了。multipart表單和上面介紹的普通表單不同,它會把表單分割成塊,表單中的每個欄位對應一個塊,每個塊都有自己的資料型別。也就是說,對於上傳欄位對應的塊,它的資料型別就可以是二進位制了:

------WebKitFormBoundaryqgkaBn8IHJCuNmiW
Content-Disposition: form-data; name="firstName"
Charles
------WebKitFormBoundaryqgkaBn8IHJCuNmiW
Content-Disposition: form-data; name="lastName"
Xavier
------WebKitFormBoundaryqgkaBn8IHJCuNmiW
Content-Disposition: form-data; name="email"
[email protected]
------WebKitFormBoundaryqgkaBn8IHJCuNmiW Content-Disposition: form-data; name="username" professorx ------WebKitFormBoundaryqgkaBn8IHJCuNmiW Content-Disposition: form-data; name="password" letmein01 ------WebKitFormBoundaryqgkaBn8IHJCuNmiW Content-Disposition: form-data; name="profilePicture"; filename="me.jpg" Content-Type: image/jpeg [[ Binary image data goes here ]] ------WebKitFormBoundaryqgkaBn8IHJCuNmiW--

在上面這個請求就是mutipart 請求,最後一個欄位profilePicture有自己的Content-Type,值是image/jpeg,而其它欄位都是簡單的文字型別。

雖然mutipart請求看起來比較複雜,但是在spring mvc中處理起來是非常簡單的。在寫我們處理上傳檔案的controller之前,我們得先配置一個Mutipart Resolver來告訴DispatchServlet如何解析一個mutipart 請求。

二、配置mutipart resolver

實現檔案上傳,其實就是解析一個Mutipart請求。DispatchServlet自己並不負責去解析mutipart 請求,而是委託一個實現了MultipartResolver介面的類來解析mutipart請求。在Spring3.1之後Spring提供了兩個現成的MultipartResolver介面的實現類:

  1. CommonMutipartResolver:通過利用Jakarta Commons FileUpload來解析mutipart 請求
  2. StandardServletMutipartResolver:依賴Servlet3.0來解析mutipart請求

所以要實現檔案上傳功能,只需在我們的專案中配置好這兩個bean中的任何一個即可。其實這兩個都很好用,如果我們部署的容器支援Servlet3.0,我們完全可以使用StandardServletMutipartResolver。但是如果我們的應用部署的容器不支援Servlet3.0或者用到的Spring版本是3.1以前的,那麼我們就需要用到CommonMutipartResolver了。下面就具體介紹一下兩種bean的配置,當然也是實現檔案上傳的兩種配置。

方式一: 通過StandardServletMutipartResolver解析mutipart 請求

1.配置multipartResolver的bean

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
    <property name="prefix" value="/WEB-INF/views/" />
    <property name="suffix" value=".jsp" />
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
</bean>

<bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver"/>

2.配置MutipartResolver相關屬性

StandardServletMutipartResolver依賴於Servlet3.0,所以要想使用StandardServletMutipartResolver,我們還必須在DispatchServlet配置裡面 註冊一個 MultipartConfigElement元素,具體配置方式如下:

<servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class>
    <load-on-startup>1</load-on-startup>
    <multipart-config>
        <location>/tmp/spittr/uploads</location>
        <max-file-size>2097152</max-file-size>
        <max-request-size>4194304</max-request-size>
    </multipart-config>
</servlet>

mutipart-config裡面有三個配置項:

  1. location:上傳檔案用到的臨時資料夾,是一個絕對路徑,需要注意,這個屬性是必填
  2. max-file-size:上傳檔案的最大值,單位是byte,預設沒有限制
  3. max-request-size:整個mutipart請求的最大值,單位是byte,預設沒有限制

方式二:通過CommonMutipartResolver 解析mutipart 請求

當然,如果我們部署的容器不是Servlet3.0,我們還可以使用CommonMutipartResolver,不過這個需要依賴Apache的commons-fileupload第三方類庫。

1.配置第三方依賴

<dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.1</version>
</dependency>

2.配置multipartResolver的bean

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
    <property name="prefix" value="/WEB-INF/views/" />
    <property name="suffix" value=".jsp" />
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
       <property name="maxUploadSize" value="100000" />
       <property name="maxInMemorySize" value="100000" />
</bean>

使用CommonMutipartResolver不需要在Servlet中配置MultipartConfigElement元素,上傳檔案的location屬性也是可選的。

大家可能有個小疑問,上面兩種方式都配置了一個id=”multipartResolver”的bean,那麼DispatchServlet是如何找到這個bean的呢?我們可以看一下DispatchServlet的原始碼,裡面有這麼一個方法:

 private void initMultipartResolver(ApplicationContext context) {
    try {
        this.multipartResolver = (MultipartResolver)context.getBean("multipartResolver", MultipartResolver.class);
        if(this.logger.isDebugEnabled()) {
            this.logger.debug("Using MultipartResolver [" + this.multipartResolver + "]");
        }
    } catch (NoSuchBeanDefinitionException var3) {
        this.multipartResolver = null;
        if(this.logger.isDebugEnabled()) {
            this.logger.debug("Unable to locate MultipartResolver with name \'multipartResolver\': no multipart request handling provided");
        }
    }

}

這個方法會預設從Spring的上下文中獲取id為multipartResolver的bean作為它的MutipartResolver。

三、寫一個上傳檔案的controller

按照上面的任何一種方式配置好,Spring就已經準備好接受mutipart請求了,下面就需要寫一個controller來接收上傳的檔案了,請看程式碼:

@Controller
public class FileUploadController {
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    @ResponseBody
    public  String uploadFileHandler( @RequestParam("file") MultipartFile file) {
        if (!file.isEmpty()) {
            try {
                // 檔案存放服務端的位置
                String rootPath = "d:/tmp";
                File dir = new File(rootPath + File.separator + "tmpFiles");
                if (!dir.exists())
                    dir.mkdirs();
                // 寫檔案到伺服器
                File serverFile = new File(dir.getAbsolutePath() + File.separator + file.getOriginalFilename());
                file.transferTo(serverFile);
                return "You successfully uploaded file=" +  file.getOriginalFilename();
            } catch (Exception e) {
                return "You failed to upload " +  file.getOriginalFilename() + " => " + e.getMessage();
            }
        } else {
            return "You failed to upload " +  file.getOriginalFilename() + " because the file was empty.";
        }
    }
}

uploadFileHandler方法中有一個引數file,它的型別是MutipartFile,也就是說Spring 會自動把mutipart請求中的二進位制檔案轉換成MutipartFile型別的物件,這麼做有什麼好處呢?我們具體看一下MutipartFile這個介面:

public interface MultipartFile {
    String getName();
    String getOriginalFilename();
    String getContentType();
    boolean isEmpty();
    long getSize();
    byte[] getBytes() throws IOException;
    InputStream getInputStream() throws IOException;
    void transferTo(File var1) throws IOException, IllegalStateException;
}

我們可以看到MutipartFile介面提供了很多方法,諸如獲取上傳檔案的名稱、內容型別、大小等等,甚至還提供了轉換成File型別檔案的方法。想想如果我們接收到僅僅是一個位元組陣列,那用起來該多麼麻煩,感激這個MutipartFile吧。

四、寫個upload.jsp頁面測試一下

我們的頁面程式碼:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
    <head>
       <title>Upload File Request Page</title>
    </head>
    <body>
        <form method="POST" action="uploadFile" enctype="multipart/form-data">
           File to upload: <input type="file" name="file">
           <input type="submit" value="Upload"> Press here to upload the file!
        </form>
    </body>
</html>

其中只有一點需要注意,就是表單的enctype屬性,這個屬性值multipart/form-data會告訴瀏覽器我們提交的是一個Mutipart請求而不是一個普通的form請求。

看一下頁面效果:

這裡寫圖片描述

執行程式,試著上傳一個檔案吧。

相關推薦

Spring MVC 檔案(upload files)

上傳功能是一個web應用很常用的一個功能,比如在一些社交網站上傳些圖片、視訊等。本篇文章主要研究了spring mvc是如何實現檔案上傳功能的,在具體講解spring mvc如何實現處理檔案上傳之前,必須弄明白與檔案上傳相關的multipart請求。 一、

spring mvc 檔案幫助類(留備用)

package com.service.impl; import com.entity.UploadInfo; import com.service.UploadHelp; import org.springframework.web.context.ContextLoader; import o

spring mvc --檔案檔案和其他資料一起提交

jsp: var formdata = new FormData(); formdata.append('file', $('#file')[0].files[0]); //上傳檔案 formdata.append('id', $('#id').val(

Spring mvc檔案

SpringMVC+表單實現檔案上傳 前端程式碼: <form action="userHead" method="post" enctype="multipart/form-data" >  <input type="file" id="uploa

spring mvc檔案功能

在web開發中,我們經常需要上傳檔案。檔案上傳在html裡通過表單來提交,但是後臺是如何獲取檔案的呢? MultipartHttpServletRequest multipartHttpServletRequest = (MultipartH

spring boot 檔案出錯:java.io.IOException: The temporary upload location

現象: 上傳excel,出現報錯: [Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: Could not parse multipart

spring boot檔案 The temporary upload location is not valid

Caused by: java.io.IOException: The temporary upload location [C:\Users\coffee\AppData\Local\Temp\tomcat.8572785615189560421.9999\w

Spring MVC 、下載、顯示圖片

title type sta direct 自動 ctu tco path stp 通過這篇文章你可以了解到: 使用 SpringMVC 框架,上傳圖片,並將上傳的圖片保存到文件系統,並將圖片路徑持久化到數據庫 在 JSP 頁面上實現顯示圖片、下載圖片 [TOC] 1.

Spring框架學習(8)spring mvc下載

class tor XML smart details targe resp imp common 內容源自:spring mvc上傳下載 如下示例: 頁面: web.xml: <?xml version="1.0" encoding="UTF-8"?>

Spring Boot檔案出錯,Required request part fileis not present

先上程式碼: @RestController @RequestMapping("/file") //@PreAuthorize(“hasAuthority(ROLE_USER)”) public class FileController { /** * 提取檔案上傳的公用程式碼

根據request,檔案(使用Spring CommonsMultipartResolver 檔案

/**      * 根據request,獲取上傳的非結構化資料      * 備註:非結構化資料會儲存臨時檔案,並返回臨時檔案路徑的集合      *      

spring-boot檔案,臨時檔案地址無效

org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; nested exception is java.io.IOException: The temporar

spring Boot 檔案,10天后,不能的bug

起因           公司研發人員 部署服務在阿里雲 ecs 伺服器; 上傳檔案過1周左右檔案自動丟失; 排查思路:     (1).查詢tomcat 啟動日誌出現如下資訊:   

使用spring boot 檔案

轉自:https://blog.csdn.net/terry7/article/details/61921362   版權宣告:本文為博主原創文章,未經博主允許不得轉載。    https://blog.csdn.net/terry7/article/

spring boot 檔案

上傳重點思路:     1、為保證伺服器安全,上傳檔案應該放在外界無法直接訪問的目錄下,比如放於WEB-INF目錄下。   2、為防止檔案覆蓋的現象發生,要為上傳檔案產生一個唯一的檔名。   3、為防止一個目錄下面出現太多檔案,要使用hash演算法打散儲存。

springboot(十七):使用Spring Boot檔案

上傳檔案是網際網路中常常應用的場景之一,最典型的情況就是上傳頭像等,今天就帶著帶著大家做一個Spring Boot上傳檔案的小案例。 1、pom包配置 我們使用Spring Boot最新版本1.5.9、jdk使用1.8、tomcat8.0。 <parent&g

Spring Boot檔案到FastDFS

1.pom加上依賴 <dependency> <groupId>org.csource</groupId> <artifactId>fastdfs-client-java</artifactId>

spring框架檔案原理探究

    <bean id="multipartResolver"           class="org.springframework.web.multipart.commons.CommonsMultipartRe

Spring MVC圖片,Java二進位制圖片寫入資料庫,生成略縮圖

步驟:1.將圖片上傳到伺服器的一個磁碟目錄下。 2.將剛才上傳好的圖片寫入資料庫image欄位。 一、上傳圖片:使用的是spring mvc 對上傳的支援。 jsp 頁面: <form name="uploadForm" id="uploadForm" m

spring boot 檔案出錯:org.springframework.web.multipart.MultipartException: Could not parse multipart s

一個國慶假期回來,測試跟我說以前好好的檔案上傳不能用了,還是真實環境,程式報如下錯誤: org.springframework.web.multipart.MultipartException: Cou