SpringBoot文件上传+进度条
一、环境搭建
1)新建SpringBoot项目,勾选 web 和 thymeleaf 依赖。
<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>
二、接口编写
@Controller public class FileController { @ResponseBody @PostMapping("upload") public String upload(MultipartFile file, HttpServletRequest request, HttpServletResponse response) { if (file.isEmpty()) return "文件为空!"; // 获取当前时间 String current_date = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date()); // 保存文件的目录 String folder = request.getServletContext().getRealPath("/img") + current_date; // 判断是否需要创建目录 File folderFile = new File(folder); if (!folderFile.exists()) folderFile.mkdirs(); String filename = file.getOriginalFilename(); // 文件名 filename = UUID.randomUUID().toString().replace("-", "") + filename.substring(filename.lastIndexOf(".")); try { File destFile = new File(folderFile, filename); System.out.println(destFile.getAbsolutePath()); file.transferTo(destFile); String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/img" + current_date + filename; System.out.println(String.format("上传成功,图片路径:%s", url)); return "success"; } catch (IOException e) { return "上传失败!"; } } }
三、前端上传页面 index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>文件上传</title> </head> <body> <div align="center"> <input type="file" id="pic" name="pic"/> <input type="button" value="上传图片" onclick="uploadFile()" /> </div> <div id="progressBar" style="padding:0px;border:solid black 0px;visibility:hidden"> <table width="300" border="0" cellspacing="0" cellpadding="0" align="center"> <tr> <td align="center" id="progressPersent">0%</td> </tr> <tr> <td> <!-- 黑色边框部分 --> <table width="100%" border="1" cellspacing="0" cellpadding="0" bordercolor="#000000"> <tr> <td> <!-- 红色部分 --> <table width="1%" border="0" cellspacing="0" cellpadding="0" bgcolor="#FF0000" id="progress"> <tr> <td> </td> </tr> </table> </td> </tr> </table> </td> </tr> <tr> <td align="center" id="complete">completed</td> </tr> </table> </div> <script> var xhr = new XMLHttpRequest(); // 上传失败处理 function uploadFailed(evt) { console.log(evt); document.getElementById("progressBar").style.visibility = "hidden"; document.getElementById("complete").innerText = evt.value(); } // 侦察附件上传情况,这个方法大概0.05-0.1秒执行一次 function onprogress(evt) { document.getElementById("progressBar").style.visibility = "visible"; var loaded = evt.loaded; // 已经上传大小情况 var total = evt.total; // 附件总大小 var per = Math.floor(100 * loaded / total); // 已经上传的百分比 document.getElementById("progressPersent").innerText = per + "%"; document.getElementById("progress").style.width = per + "%"; } // 上传文件 function uploadFile() { // 1. 将上传的文件放入FormData中 var fileList = document.getElementById("pic").files; var formData = new FormData(); formData.append("file", fileList[0]); // 监听事件 xhr.upload.addEventListener("progress", onprogress, false); xhr.addEventListener("error", uploadFailed, false); // 请求方式 接口 true:异步请求 xhr.open("POST", "upload", true); xhr.send(formData); // 带上数据 xhr.onreadystatechange = function (ev) { if (xhr.readyState == 4 && xhr.status == 200) { if (xhr.responseText == "success") { document.getElementById("progress").style.width = "100%"; document.getElementById("progressPersent").innerText ="100%" ; document.getElementById("complete").innerText ="上传成功!" ; }else { document.getElementById("complete").innerText ="上传失败!" ; } } } } </script> </body> </html>
四、测试上传
1)SpringBoot 默认配置的 最大文件上传大小 和 最大请求大小 都是10MB,为了能够清楚看到进度条效果配置成120MB。
spring: servlet: multipart: max-file-size: 120MB max-request-size: 120MB thymeleaf: cache: false
2)运行程序,我选择了一个60MB左右的文件上传。
转载自:https://jingyan.baidu.com/article/ceb9fb1064774b8cad2ba096.html
致力于记录学习过程中的笔记,希望大家有所帮助(*^▽^*)!