后端接口代码:
@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/[email protected]/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 * 100
sliderBar.style.width = `${percentage}%`
document.querySelector(".percentage").innerHTML = `${percentage.toFixed(2)}`
})
xhr.open('post', 'http://localhost:80/upload')
xhr.send(fd)
}
</script>
效果: