天天看點

Spring Boot2.x檔案上傳簡單案例Spring Boot檔案上傳簡單案例

SpringBoot2.x檔案上傳簡單案例

  • Spring Boot檔案上傳簡單案例
    • 1. 建立工程
    • 2. pom.xml檔案
    • 2. application.yml
    • 3.前端fileupload.html
    • 4. 後端控制器

Spring Boot檔案上傳簡單案例

本案例環境:
  1. SpringBoot: 2.3.0.RELEASE
  2. JDK: 1.8
  3. 模闆: thymeleaf

1. 建立工程

在IDEA中通過SpringBoot初始化向導建立一個名稱為yuan-fileupload的工程

2. 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.3.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>org.yuan</groupId>
    <artifactId>yuan-fileupload</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>yuan-fileupload</name>
    <description>Demo project for Spring Boot</description>

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

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.4</version>
        </dependency>



        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

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

</project>

           

2. application.yml

server:
  port: 8085
spring:
  servlet:
    multipart:
      max-file-size: 1GB # 單個檔案上傳的大小
      max-request-size: 1GB # 上傳的總檔案大小
           

3.前端fileupload.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>檔案上傳案例</title>
</head>
<body>
    
<form method="post" enctype="multipart/form-data" th:action="${#httpServletRequest.getContextPath()}+'/fileUpload'">
    檔案1: <input type="file" name="files"><br>
    檔案2: <input type="file" name="files"><br>
    <input type="submit" value="上傳">
</form>
</body>
</html>
           

4. 後端控制器

FileUploadController.Java如下:

package org.yuan.yuanfileupload.fileupload;

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.yuan.yuanfileupload.utils.ResultMsg;

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

/**
 * <p>
 * Description: 檔案上傳簡單案例 <br>
 * <p>
 * Author:jinshengyuan <br>
 * Datetime: 2020/5/24 14:55
 * </p>
 *
 * @since 2020/5/24 14:55
 */
@Controller
public class FileUploadController {

    /**
     * <p>
     * Description: 跳轉至檔案上傳頁面的handler <br>
     * <p>
     * Author:jinshengyuan <br>
     * Datetime: 2020/5/24 14:56
     * </p>
     *
     * @return 跳轉的模闆名稱
     * @since 2020/5/24 14:56
     */
    @RequestMapping("/initUpload")
    public String initUpload() {
        return "fileUpload";
    }


    /**
     * <p>
     * Description: 檔案上傳方法<br>
     * <p>
     * Author:jinshengyuan <br>
     * Datetime: 2020/5/24 14:57
     * </p>
     *
     * @return 傳回上傳後的處理結果
     * @since 2020/5/24 14:57
     */
    @ResponseBody
    @RequestMapping("/fileUpload")
    public ResultMsg fileUpload(MultipartFile[] files, HttpServletRequest request) throws Exception {
        for (MultipartFile file : files) {
            String contentType = file.getContentType();
            String originalFilename = file.getOriginalFilename();
            String name = file.getName();
            System.out.println("contentType:" + contentType);
            System.out.println("originalFilename:" + originalFilename);
            System.out.println("name:" + name);
            //檔案名不為空則上傳
            if (!StringUtils.isEmpty(originalFilename)) {
                //檔案存放位置
                //1.傳統的方式擷取伺服器跟目錄下的fileUpload路徑
                //String realPath = request.getServletContext().getRealPath("/fileUpload");
                //2.Springboot項目中擷取resource/static/fileupload路徑
                String uploadPath = ResourceUtils.getURL("classpath:").getPath() + "static/fileUpload/";
                System.out.println("uploadPath:" + uploadPath);
                //檔案輸出目錄是否存在,不存在則建立
                File dir = new File(uploadPath);
                if (!dir.exists()) {
                    dir.mkdir();
                }
                //檔案名字首 日期+UUID
                String fileNamePrefix = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + UUID.randomUUID().toString().replace("-", "");
                //檔案字尾名
                String fileExtendName = FilenameUtils.getExtension(originalFilename);
                //輸出到指定的位置
                String outFileName = fileNamePrefix.concat(".").concat(fileExtendName);
                //檔案上傳至指定目錄
                file.transferTo(new File(dir, outFileName));

            } else {
                //檔案名為空,跳出目前循環
                continue;
            }
        }
        return ResultMsg.success();
    }
}