Spring-Boot-2-X-實現文件上傳(三)

使用 SpringBoot 項目完成單個、多個文件的上傳處理,並將上傳的文件保存到指定目錄下。
代碼演示案例
全部的 HTML 頁面文件
index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>選擇上傳文件類型</title>
</head>
<script language="javascript">
    function single() {
        document.form1.action = "/singlefile";
        document.form1.submit();
    }

    function multi() {
        document.form1.action = "/multifile";
        document.form1.submit();
    }
</script>
<body>
<form name="form1" method="post">
    <input type="button" name="btn1" value="單個文件上傳" onclick="single();">
    <input type="button" name="btn2" value="多個文件上傳" onclick="multi();">
</form>
</body>
</html>

multifile.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>多文件上傳</title>
</head>
<body>
<h1 th:inlines="text">多文件上傳</h1>
<form action="/multiFileUpload" method="post" enctype="multipart/form-data">
    <p>選擇文件1: <input type="file" name="fileName"/></p>
    <p>選擇文件2: <input type="file" name="fileName"/></p>
    <p>選擇文件3: <input type="file" name="fileName"/></p>
    <p><input type="submit" value="提交"/></p>
</form>
</body>
</html>

singlefile.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>單文件上傳</title>
</head>
<body>
<h1 th:inlines="text">單文件上傳</h1>
<form action="/singleFile" method="post" enctype="multipart/form-data">
    <p>文件:<input type="file" name="head_img"/></p>
    <p><input type="submit" value="上傳"/></p>
</form>
</body>
</html>
邏輯代碼
定義結果集

@Getter
@Setter
@ToString
public class Result implements Serializable {

    private boolean flag; //是否成功
    private Integer code; //返回碼
    private String message;//返回信息

    public Result(boolean flag, Integer code, String message) {
        this.flag = flag;
        this.code = code;
        this.message = message;
    }
}

定義錯誤碼
public class StatusCode {
    public static final int OK = 2000;       //成功
    public static final int ERROR = 4000;    //失敗
}

邏輯代碼
@Controller
@Slf4j
public class FileController {

    @Value("${file.path}")
    private String filePath;

    // 獲取 singlefile.html 頁面
    @RequestMapping(value = "/singlefile", method = RequestMethod.POST)
    public String single() {

        return "singlefile";
    }

    // 單文件上傳
    @RequestMapping(value = "singleFile")
    @ResponseBody
    public Result uploadFile(@RequestParam("head_img") MultipartFile file, HttpServletRequest request) {

        if (file.isEmpty()) {
            return new Result(false, StatusCode.ERROR, "上傳的文件大小爲空,請檢查!!");
        }

        //獲取文件名稱、後綴名、大小
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        long size = file.getSize();

        log.info("上傳的文件名稱爲:[{}],文件後綴爲:[{}],文件大小爲:[{}]!!", fileName, suffixName, size);

        // 存儲轉換後文件名稱
        fileName = UUID.randomUUID() + suffixName;
        log.info("轉換後的文件名爲:[{}]!!", fileName);

        File dest = new File(filePath + fileName);
        //判斷父目錄是否存在
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdir();
        }

        try {
            file.transferTo(dest);
            return new Result(true, StatusCode.OK, "上傳成功!!");
        } catch (IOException e) {
            log.error("上傳文件過程當中發生異常!", e);
        }

        return new Result(true, StatusCode.ERROR, "上傳失敗!!");
    }

    // 獲取 multifile.html 頁面
    @RequestMapping("/multifile")
    public String multi() {

        return "multifile";
    }

    // 多文件上傳
    @PostMapping(value = "multiFileUpload")
    @ResponseBody
    public Result multiFileUpload(HttpServletRequest request) {

        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("fileName");

        for (MultipartFile file : files) {

            if (file.isEmpty()) {
                return new Result(false, StatusCode.ERROR, "上傳多個文件時,某個文件大小爲空,請檢查!!");
            } else {

                String fileName = file.getOriginalFilename();
                String suffixName = fileName.substring(fileName.lastIndexOf("."));
                long size = file.getSize();

                log.info("上傳的文件名稱爲:[{}],文件後綴爲:[{}],文件大小爲:[{}]!!", fileName, suffixName, size);

                fileName = UUID.randomUUID() + suffixName;
                log.info("轉換後的文件名爲:[{}]!!", fileName);

                File dest = new File(filePath + fileName);
                if (!dest.getParentFile().exists()) {
                    dest.getParentFile().mkdir();
                }

                try {
                    file.transferTo(dest);
                } catch (IOException e) {
                    log.error("上傳文件過程當中發生異常!!", e);
                }

            }
        }
        return new Result(true, StatusCode.OK, "上傳成功!!");
    }
}

application.properties
# 端口
server.port=8082
# 配置單個文件、多個文件大小
spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=100MB
# 文件上傳保存路徑
file.path=E:/test/
# 取消模板文件緩存
spring.thymeleaf.cache=false
文件 結構目錄
1564585987055.png
相關文章
相關標籤/搜索