天天看點

Spring Boot:檔案上傳

測試代碼

​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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.2</version>
    </parent>

    <packaging>jar</packaging>

    <groupId>com.kaven</groupId>
    <artifactId>springboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <name>springboot</name>
    <description>springboot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>      

​application.properties​

​(配置檔案):

spring.servlet.multipart.max-file-size=500MB
spring.servlet.multipart.max-request-size=500MB      
  • ​max-file-size​

    ​​:指定允許上傳檔案的最大大小,預設值為​

    ​1MB​

    ​。
  • ​max-request-size​

    ​​:指定允許​

    ​multipart/form-data​

    ​​請求的最大大小,預設值為​

    ​10MB​

    ​。

上傳接口:

package com.kaven.springboot.controller;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
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.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

@RestController
public class FilesController {

    @PostMapping(value="/upload", headers="content-type=multipart/form-data")
    public String upload(@RequestParam(value = "file") MultipartFile file,
                         HttpServletResponse response) throws IOException, InterruptedException {

        System.out.println("有檔案上傳請求進來了");
        FileOutputStream fileOutputStream = null;
        InputStream inputStream = null;

        try {
            // 上傳檔案是否存在
            if (file != null && !file.isEmpty()) {
                // 如果上傳檔案存在,擷取它的原始檔案名
                String fileName = file.getOriginalFilename();
                if (StringUtils.hasText(fileName)) {
                    // 将上傳檔案存儲在伺服器的E盤下(Windows)
                    java.io.File outFile = new java.io.File("E:\\" + fileName);
                    // 基于outFile建立檔案輸出流執行個體
                    fileOutputStream = new FileOutputStream(outFile);
                    // 擷取上傳檔案的輸入流
                    inputStream = file.getInputStream();
                    /*
                    * 将位元組從輸入流複制到輸出流
                    * 此方法在内部會緩沖輸入,是以無需使用BufferedInputStream
                    * 大型流(超過2GB)将在複制完成後傳回位元組複制值-1 ,因為無法将正确的位元組數作為int傳回
                    * 對于大型流,需要使用copyLarge(InputStream, OutputStream)方法
                    * 參數:
                    * input – 要讀取的InputStream
                    * output - 要寫入的OutputStream
                    * */
                    IOUtils.copy(inputStream, fileOutputStream);
                }
            }
            else {
                // 檔案不存在
                response.setStatus(HttpStatus.BAD_REQUEST.value());
                return "檔案不存在";
            }
        } catch (Exception e) {
            // 檔案上傳錯誤
            e.printStackTrace();
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            return "檔案上傳錯誤";
        } finally {
            if (fileOutputStream != null) {
                fileOutputStream.flush();
                fileOutputStream.close();
            }
        }
        // 檔案上傳成功
        response.setStatus(HttpStatus.OK.value());
        return "檔案上傳成功";
    }
}      

啟動類:

package com.kaven.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootApplication {

    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(SpringbootApplication.class);
        application.run(args);
    }
}      

使用​

​Postman​

​進行測試。

Spring Boot:檔案上傳
Spring Boot:檔案上傳

上傳的檔案是完整的,可以播放(視訊檔案)。

Spring Boot:檔案上傳

上傳檔案不存在。

Spring Boot:檔案上傳

控制台的輸出。

Spring Boot:檔案上傳