springboot 文件上传进度条
时间: 2023-08-19 08:09:30 浏览: 142
在Spring Boot中实现文件上传进度条可以通过以下步骤完成:
1. 配置依赖:在pom.xml文件中添加`spring-boot-starter-web`和`spring-boot-starter-thymeleaf`依赖。
2. 创建上传文件页面:在src/main/resources/templates目录下创建一个名为`upload.html`的HTML文件,添加如下内容:
```html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>File Upload</title>
</head>
<body>
<h1>File Upload</h1>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file">
<br><br>
<input type="submit" value="Upload">
</form>
<br>
<div id="progress" style="display: none;">
<progress id="progressbar" value="0" max="100"></progress>
<span id="status"></span>
</div>
<script>
var form = document.querySelector('form');
var fileInput = document.querySelector('#file');
var progressBar = document.querySelector('#progressbar');
var status = document.querySelector('#status');
form.addEventListener('submit', function(event) {
event.preventDefault();
var file = fileInput.files[0];
var formData = new FormData();
formData.append('file', file);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener('progress', function(event) {
var percent = (event.loaded / event.total) * 100;
progressBar.value = percent;
status.innerText = percent.toFixed(2) + '% uploaded';
});
xhr.open('POST', '/upload');
xhr.onload = function() {
progressBar.style.display = 'none';
status.innerText = 'Upload complete!';
};
progressBar.style.display = 'block';
xhr.send(formData);
});
</script>
</body>
</html>
```
3. 创建文件上传控制器:创建一个名为`FileUploadController.java`的Java类,添加如下内容:
```java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
@Controller
@RequestMapping("/")
public class FileUploadController {
@GetMapping("/")
public String showUploadForm() {
return "upload";
}
@PostMapping("/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file) throws IOException {
// 设置上传文件存储路径
Path uploadDir = Path.of("uploads");
if (!Files.exists(uploadDir)) {
Files.createDirectory(uploadDir);
}
// 复制文件到指定路径
Path targetLocation = uploadDir.resolve(file.getOriginalFilename());
Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
return "redirect:/";
}
}
```
4. 运行应用程序:运行Spring Boot应用程序,访问`http://localhost:8080`即可看到文件上传页面。选择一个文件并点击“Upload”按钮,进度条将显示文件上传进度。
通过以上步骤,你可以在Spring Boot中实现文件上传进度条。请注意,这只是一个基本示例,你可以根据自己的需求进行修改和扩展。
阅读全文