天天看點

Spring Boot(六):檔案上傳

檔案上傳的操作

基本上每一個項目都涉及檔案上傳這個功能吧,SpringBoot同樣也提供這樣的支援。

首先,使用者需要在前台選擇一個檔案,然後通過按鈕發送請求。在以前我們的視圖層會選擇使用jsp來做,但是在SpringBoot中,不推薦這種方式,它推薦一種叫做模闆引擎的東西。

模闆引擎:

  1. Freemarker:檔案一般儲存為 xxx.ftl
  2. Thymeleaf (主推),直接是html結尾

至于模闆引擎,後續的文章會推出,因為這裡會用到,是以提一下。要想讓SpringBoot成功傳回頁面,就需要導入相關的限制了,這裡就以Thymeleaf為例。

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
           

當然,還需要web相關的限制。

然後在resources目錄下的templates檔案夾建立index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form enctype="multipart/form-data" method="post" action="/upload">
        檔案:<input type="file" name="file" /><br/>
        姓名:<input type="text" name="name"><br/>
<input type="submit" value="上傳"/>
    </form>
</body>
</html>
           

隻是做個示範,就沒有什麼樣式可說了,然後請求位址已經寫好,就讓後端來處理邏輯吧。

package com.qfcwx.springbootfileupload.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @ClassName: FileController
 * @Author: 清風一陣吹我心
 * @Description: TODO
 * @Date: 2019/3/9 12:51
 * @Version 1.0
 **/
@RestController
public class FileController {

    private static final String FILE_PATH = "D:/idea_workspace/SpringBootDemo/SpringBoot/springboot-fileupload/src/main/resources/images/";


    @PostMapping(value = "/upload")
    public String upload(@RequestParam("file")MultipartFile file, HttpServletRequest request){

        String name = request.getParameter("name");
        System.out.println("使用者名:"+name);

        //擷取檔案名
        String fileName = file.getOriginalFilename();
        System.out.println("上傳的檔案名:" + fileName);

        //擷取檔案的字尾名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //擷取檔案字首
        String prefixName = fileName.substring(0, fileName.lastIndexOf("."));

        //上傳檔案後的名稱
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd-HHmmss");
        String date = dateFormat.format(new Date());

        fileName = prefixName + date + suffixName;
        File dest = new File(FILE_PATH + fileName);

        try {
            file.transferTo(dest);
            return name+"上傳檔案成功,上傳後的檔案名為:"+fileName;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上傳失敗!";
    }
}
           

FILE_PATH:指上傳後檔案的儲存路徑。

MultipartFile:實則是SpringMvc提供的一種操作檔案上傳的類。

file.getOriginalFilename():這個方法可以擷取對象中的檔案名。

我這裡取檔案的字首和字尾,然後加上一個時間戳,作為儲存檔案的名稱。

file.transferTo(dest):方法将上傳檔案寫到伺服器上指定的檔案。

以前傳檔案是以流的形式來讀取和寫入,使用這種方式可以更友善的操作檔案。

基本上所有配置和代碼都搞定了,下面就是測試環節了,啟動項目。

Spring Boot(六):檔案上傳

首先看到這個界面,然後選擇檔案,填寫使用者名,點選上傳按鈕。

Spring Boot(六):檔案上傳

然後看到傳回了這一串東西,證明檔案上傳成功。

如果你以為這麼簡單就完了麼?實際上不是這樣。傳檔案的搞定了,可是上傳檔案的大小呢?倘若你想傳一首歌,就會發現,背景會抛出異常。

是以,我們還需要對檔案大小限制做修改。SpringBoot預設限制檔案大小不能超過1MB,這也忒小了。

解決辦法分兩種:

(一)使用java代碼來配置bean。

@Bean
    public MultipartConfigElement multipartConfigElement(){
        MultipartConfigFactory factory = new MultipartConfigFactory();
        factory.setMaxFileSize(DataSize.ofMegabytes(20));
        factory.setMaxRequestSize(DataSize.ofMegabytes(30));
        return factory.createMultipartConfig();
    }
           

在啟動類中加入上面的代碼即可。

factory.setMaxFileSize:設定單個檔案的大小。

factory.setMaxRequestSize:設定總上傳的資料大小。

DataSize是以前沒使用過的類,但是看API文檔,上面有詳細的介紹。

"12KB"  -- parses as "12 kilobytes"
 "5MB"  -- parses as "5 megabytes"
 "20"   -- parses as "20 bytes"
           

大概意思就是:

如果想限制為KB大小,就使用DataSize.ofKilobytes()這個方法。

如果想限制為MB大小,就使用DataSize.ofMegabytes()這個方法。

如果想限制為位元組大小,就使用DataSize.ofBytes()這個方法。

我這裡設定為20MB。然後重新開機項目,選擇一首歌上傳,就會看到成功的結果了。

(二)使用配置檔案的方式

spring.servlet.multipart.enabled=true
spring.servlet.multipart.max-file-size=20MB
spring.servlet.multipart.max-request-size=100MB
           

好,打完收工,是不是配置檔案的方式很簡單呢,就這麼一丢丢~這就是SpringBoot帶來的便捷。

重新開機項目,也能長傳成功了。

後面的示範,就不放圖了。可以自己動手操作。本期到此結束,下期再見。

擁有希望的人,和滿天的星星一樣,是永遠不會孤獨的。找到和自己一樣的星星,把通往自由的路, 照亮吧!