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

配置文件

	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

Spring Boot上传文件(带进度条)的更多相关文章

  1. Extjs 使用fileupload插件上传文件 带进度条显示

    一.首先我们看看官方给出的插件的解释: 一个文件上传表单项具有自定义的样式,并且可以控制按钮的文本和 像文本表单的空文本类似的其他特性. 它使用一个隐藏的文件输入元素,并在用户选择文件后 在form提 ...

  2. asp.net mvc 实现上传文件带进度条

    本文乃是博主早期写的,此种思路虽然实现了,但固然不是最好的,仅做参考学习. 可以用js onprogress .fileinput .webuploader.jq ajaxsubmit等实现 思路:a ...

  3. FormData上传文件 带进度条

    * jQuery ajax  FormData 上传文件 template $.ajax({ url: url, type: 'POST', data: new FormData(form), dat ...

  4. ASP.NET Jquery+ajax上传文件(带进度条)

    效果图 支持ie6+,chrome,ie6中文文件名会显示乱码. 上传时候会显示进度条. 需要jquery.uploadify.js插件,稍后会给出下载 前台代码 <%@ Page Langua ...

  5. java进行文件上传,带进度条

    网上看到别人发过的一个java上传的代码,自己写了个完整的,附带源码 项目环境:jkd7.tomcat7. jar包:commons-fileupload-1.2.1.jar.commons-io-1 ...

  6. springboot(十七):使用Spring Boot上传文件

    上传文件是互联网中常常应用的场景之一,最典型的情况就是上传头像等,今天就带着带着大家做一个Spring Boot上传文件的小案例. 1.pom包配置 我们使用Spring Boot最新版本1.5.9. ...

  7. (转)Spring Boot(十七):使用 Spring Boot 上传文件

    http://www.ityouknow.com/springboot/2018/01/12/spring-boot-upload-file.html 上传文件是互联网中常常应用的场景之一,最典型的情 ...

  8. 使用Spring Boot上传文件

    原文:http://www.cnblogs.com/ityouknow/p/8298344.html 上传文件是互联网中常常应用的场景之一,最典型的情况就是上传头像等,今天就带着带着大家做一个Spri ...

  9. Spring Boot(十七):使用 Spring Boot 上传文件

      上传文件是互联网中常常应用的场景之一,最典型的情况就是上传头像等,今天就带着带着大家做一个 Spring Boot 上传文件的小案例. 1.pom 包配置 我们使用 Spring Boot 版本 ...

随机推荐

  1. Pop!_OS下安装C++编程工具

    Pop!_OS下C++编程 #0x0 Visual Studio Code #0x1 C++ 0x11 code::blocks #0x0 Visual Studio Code 下载安装vscode ...

  2. python网络编程05 /TCP阻塞机制

    python网络编程05 /TCP阻塞机制 目录 python网络编程05 /TCP阻塞机制 1.什么是拥塞控制 2.拥塞控制要考虑的因素 3.拥塞控制的方法: 1.慢开始和拥塞避免 2.快重传和快恢 ...

  3. Python面向对象02/类的空间问题、类与对象之间的关系、类与类之间的关系

    Python面向对象02/类的空间问题.类与对象之间的关系.类与类之间的关系 目录 Python面向对象02/类的空间问题.类与对象之间的关系.类与类之间的关系 1. 类的空间问题 2. 类与对象之间 ...

  4. How to start MySQL on Linux

    启动MySQL数据库 service mysql start 查看MySQL进程 ps -ef |grep mysql 查看MySQL端口号 cd /etc/init.d/ netstat -atnp ...

  5. bzoj3791作业*

    bzoj3791作业 题意: 对一个01序列进行染色,每次能将一个区间染上色(可覆盖之前染的),共能染k次,求最大正确染色个数.n≤100000,m≤50. 题解: 结论:染k次最多能把序列分成2*k ...

  6. git怎么合并远程分支

    一共就五步: 1.把代码clone到本地仓库 git clone https://github.com/573734817pc/shop.git 2.在本地创建dev分支并与远程dev分支对应 git ...

  7. Mysql数据库搭建集群---实现主从复制,读写分离

    参考博客:https://blog.csdn.net/xlgen157387/article/details/51331244 A.  准备:多台服务器,且都可以互相随意访问root用户,都可以随意进 ...

  8. Burp Suite Report - 报告功能

    1. 通过点击Host选择不同的颜色,可以设置严重性: 2.生成网页版应用分析报告:选中所有条目->右击网址,保存所有选中项目,存储格式为html.

  9. kubernetes系列(十七) - 通过helm安装dashboard详细教程

    1. 前提条件 2. 配置https证书为secret 3. dashboard安装 3.1 helm拉取dashboard的chart 3.2 配置dashboard的chart包配置 3.3 he ...

  10. 切换npm源的几种方法

    我们在使用官方提供的npm源安装各种依赖包的时候,下载速度会很慢,通常需要更换npm源. 我们可以在终端中输入命令 npm config list 来查看 npm 源地址,默认地址为 metrics- ...