(轉)Spring Boot 上傳文件(帶進度條)

轉:Spring Boot上傳文件(帶進度條) - 爲你撐起一片天 - 博客園 (cnblogs.com)

配置文件

	spring:
  		freemarker:
			template-loader-path: classpath:/static/
		##Spring Boot 2.x 配置上傳文件大小
		servlet:
			multipart:
  				max-file-size: 500MB
  				max-request-size: 500MB

InfoMsg Bean##

    public class InfoMsg {
	    private String code;
	    private String msg;
	
	    public String getCode() {
	        return code;
	    }
	
	    public void setCode(String code) {
	        this.code = code;
	    }
	
	    public String getMsg() {
	        return msg;
	    }
	
	    public void setMsg(String msg) {
	        this.msg = msg;
	    }

}

Controller##

@Controller
@RequestMapping("/upload")
public class UploadController {
    private static final String TMP_PATH = "D:/projects/tmp";

    @GetMapping
    public String fileUp() {

        return "upload";
    }

    @ResponseBody
    @PostMapping
    public InfoMsg fileUpload(@RequestParam("uploadFile") MultipartFile file) {
        InfoMsg infoMsg = new InfoMsg();
        if (file.isEmpty()) {
            infoMsg.setCode("error");
            infoMsg.setMsg("Please select a file to upload");
            return infoMsg;
        }
        try {
            File tmp = new File(TMP_PATH, file.getOriginalFilename());
            if (!tmp.getParentFile().exists()) {
                tmp.getParentFile().mkdirs();
            }
            String[] fileInfo = getFileInfo(tmp);
            File orRenameFile = createOrRenameFile(tmp, fileInfo[0], fileInfo[1]);
            if (tmp.renameTo(orRenameFile)) {
                file.transferTo(orRenameFile);
            }else {
                file.transferTo(tmp);
            }
            infoMsg.setCode("success");
            infoMsg.setMsg("You successfully upload" + file.getOriginalFilename());
        } catch (IOException e) {
            infoMsg.setCode("error");
            infoMsg.setMsg("Uploaded file failed");
        }
        return infoMsg;

    }

	 /**
     * 創建或重命名文件
     * ps:sss.jpg    sss(1).jpg
     * @param from
     * @param toPrefix
     * @param toSuffix
     * @return
     */
    public static File createOrRenameFile(File from, String toPrefix, String toSuffix) {
        File directory = from.getParentFile();
        if (!directory.exists()) {
            if (directory.mkdir()) {
                System.out.println("Created directory " + directory.getAbsolutePath());
            }
        }
        File newFile = new File(directory, toPrefix + toSuffix);
        for (int i = 1; newFile.exists() && i < Integer.MAX_VALUE; i++) {
            newFile = new File(directory, toPrefix + "(" + i + ")" + toSuffix);
        }
        if (!from.renameTo(newFile)) {
            System.out.println("Couldn't rename file to " + newFile.getAbsolutePath());
            return from;

        }
        return newFile;
    }
	
	 /**
     * 獲取File的   . 前後字串
     * @param from
     * @return
     */
    public static String[] getFileInfo(File from) {
        String fileName = from.getName();
        int index = fileName.lastIndexOf(".");
        String toPrefix = "";
        String toSuffix = "";
        if (index == -1) {
            toPrefix = fileName;
        } else {
            toPrefix = fileName.substring(0, index);
            toSuffix = fileName.substring(index, fileName.length());
        }
        return new String[]{toPrefix, toSuffix};
    }

}

頁面upload.ftl 使用的是freemarker##

<!DOCTYPE html>
<html>
<head>
    <style type="text/css">
        progress {
            background-color: #56BE64;
        }

        progress::-webkit-progress-bar {
            background: #ccc;
        }

        progress::-webkit-progress-value {
            background: #56BE64;
        }

        percentage {
            position: fixed;
            left: 160px;
        }

    </style>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<h1>Spring Boot file upload example</h1>
<form id="FileuploadForm" method="POST" action="/upload" enctype="multipart/form-data">
    <input type="file" name="uploadFile" id="uploadFile"/><br/>
    <br/> <input type="button" id="btnUpload" value="上傳文件" onclick="upload()"/>
    <div id="msg"></div>
</form>
<!--進度條部分(默認隱藏)-->
<div style="display: none;" class="progress-body">
    <div>
        <span style="width: 100px; display: inline-block; text-align: right">上傳進度:</span>
        <progress></progress>
        <percentage>0%</percentage>
    </div>
    <div>
        <span style="width: 100px; display: inline-block; text-align: right">上傳速度:</span>
        <span style="width: 300px;" class="progress-speed">0 M/S, 0/0M</span>
    </div>
    <div>
        <span style="width: 100px; display: inline-block; text-align: right">上傳狀態:</span>
        <span style="width: 300px;" class="progress-info">請選擇文件並點擊上傳文件按鈕</span>
    </div>
</div>
<script>
    // 上傳文件
    function upload() {
        $("#msg").text("");
        var checkFile = $("#uploadFile").val();
        var msgInfo = "";
        if (null == checkFile || "" == checkFile) {
            $("#msg").text("文件爲空,請選擇文件!");
        } else {
            var formData = new FormData(document.getElementById("FileuploadForm"));
            $.ajax({
                type: "POST",
                enctype: 'multipart/form-data',
                url: '/upload',
                data: formData,
                cache: false,
                processData: false,
                contentType: false,
                error: function (result) {
                    console.log("error");
                    console.log(result);
                    flag = false;
                    $("#msg").text("訪問服務器錯誤,請重試!");
                },
                success: function (result) {
                    console.log("success");
                },
                xhr: function () {
                    var xhr = $.ajaxSettings.xhr();
                    if (xhr.upload) {
                        $("#btnUpload").attr("disabled", true);
                        $("#uploadFile").attr("disabled", true);
                        //處理進度條的事件
                        xhr.upload.addEventListener("progress", progressHandle, false);
                        //加載完成的事件
                        xhr.addEventListener("load", completeHandle, false);
                        //加載出錯的事件
                        xhr.addEventListener("error", failedHandle, false);
                        //加載取消的事件
                        xhr.addEventListener("abort", canceledHandle, false);
                        //開始顯示進度條
                        showProgress();
                        return xhr;
                    }
                }
            }, 'json');
        }
    }

    var start = 0;

    //顯示進度條的函數
    function showProgress() {
        start = new Date().getTime();
        $(
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章