ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

(转)Spring Boot 上传文件(带进度条)

2022-02-18 18:32:02  阅读:230  来源: 互联网

标签:body return String 进度条 Spring Boot file progress 上传


转: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();
        $(".progress-body").css("display", "block");
    }

    //隐藏进度条的函数
    function hideProgress() {
        $("#uploadFile").val('');
        $('.progress-body .progress-speed').html("0 M/S, 0/0M");
        $('.progress-body percentage').html("0%");
        $('.progress-body .progress-info').html("请选择文件并点击上传文件按钮");
        $("#btnUpload").attr("disabled", false);
        $("#uploadFile").attr("disabled", false);
        //$(".progress-body").css("display", "none");
    }

    //进度条更新
    function progressHandle(e) {
        $('.progress-body progress').attr({value: e.loaded, max: e.total});
        var percent = e.loaded / e.total * 100;
        var time = ((new Date().getTime() - start) / 1000).toFixed(3);
        if (time == 0) {
            time = 1;
        }
        $('.progress-body .progress-speed').html(((e.loaded / 1024) / 1024 / time).toFixed(2) + "M/S, " + ((e.loaded / 1024) / 1024).toFixed(2) + "/" + ((e.total / 1024) / 1024).toFixed(2) + " MB. ");
        $('.progress-body percentage').html(percent.toFixed(2) + "%");
        if (percent == 100) {
            $('.progress-body .progress-info').html("上传完成,后台正在处理...");
        } else {
            $('.progress-body .progress-info').html("文件上传中...");
        }
    };

    //上传完成处理函数
    function completeHandle(e) {
        $('.progress-body .progress-info').html("上传文件完成。");
        setTimeout(hideProgress, 2000);
    };

    //上传出错处理函数
    function failedHandle(e) {
        $('.progress-body .progress-info').html("上传文件出错, 服务不可用或文件过大。");
        setTimeout(hideProgress, 2000);
    };

    //上传取消处理函数
    function canceledHandle(e) {
        $('.progress-body .progress-info').html("上传文件取消。");
        setTimeout(hideProgress, 2000);
    };
</script>
</body>
</html>

效果展示##

service life image
service life image
service life image

标签:body,return,String,进度条,Spring,Boot,file,progress,上传
来源: https://www.cnblogs.com/wangle1001986/p/15910913.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有