当前位置: 首页> 健康> 知识 > 前后端实现文件上传进度条-实时进度

前后端实现文件上传进度条-实时进度

时间:2025/7/12 5:39:31来源:https://blog.csdn.net/qq_45338391/article/details/139449203 浏览次数:0次

后端接口代码:

 @PostMapping("/upload")public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) {try {// 获取文件名String fileName = file.getOriginalFilename();// 创建上传目标路径Path targetPath = Paths.get(System.getProperty("user.dir")+"/file", fileName);// 保存文件到本地Files.copy(file.getInputStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);// 返回上传成功信息return ResponseEntity.ok().body("File uploaded successfully: " + fileName);} catch (IOException e) {e.printStackTrace();// 返回上传失败信息return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to upload file: " + e.getMessage());}}

前端代码:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"><head><meta  http-equiv="Content-Type" charset="UTF-8"><title>文件上传进度条</title><meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"><meta name="description" content=""><meta name="author" content=""><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous"><link rel="stylesheet" href="css/sl.css"><style>body {display: flex;flex-direction: column;justify-content: center;align-items: flex-start;}.uploader {display: flex;align-items: center;}.slider-track {width: 70vw;height: 8px;background-color: #080101;margin: 20px 10px 20px 0;border-radius: 4px;}.slider-bar {height: 8px;width: 0px;border-radius: inherit;background-image: linear-gradient(to right, #018eb2, #29c9eb);transition: width;}</style>
</head>
<body><input type="file" onchange="uploadFile(this.files)">
<div class="uploader"><div class="slider-track"><div class="slider-bar"></div></div><div><span class="percentage">0</span>%</div>
</div></body>
</html>
<script type="text/javascript" src="js/jquery-1.8.3-source.js"></script>
<script>function uploadFile(files) {let fd = new FormData();//fd.append('file', files[0], "2.jpg")//设置第三个参数,就按第三个格式和名称来 不建议fd.append('file', files[0])//不设置第三个参数,就上传什么文件存什么文件格式let xhr = new XMLHttpRequest();let sliderBar = document.querySelector(".slider-bar")sliderBar.style.width = "0"xhr.upload.addEventListener("progress", function (e) {let percentage = e.loaded / e.total * 100sliderBar.style.width =  `${percentage}%`document.querySelector(".percentage").innerHTML = `${percentage.toFixed(2)}`})xhr.open('post', 'http://localhost:80/upload')xhr.send(fd)}
</script>

效果:
在这里插入图片描述
在这里插入图片描述

关键字:前后端实现文件上传进度条-实时进度

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: