springboot3.0文件上传进度条
时间: 2025-05-11 15:14:43 浏览: 21
### 实现Spring Boot 3.0中的文件上传进度条
为了实现在Spring Boot 3.0中文件上传时显示进度条的功能,可以按照以下方法进行设置。
#### 后端配置与编码
在后端部分,主要依赖于`StandardServletMultipartResolver`来解析multipart请求并监听其传输状态。通过自定义拦截器或过滤器,在接收到分片数据包时更新当前已接收的数据量,并将其反馈给客户端用于渲染进度条。
```java
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@RestController
@RequestMapping("/api/file")
public class FileUploadController {
@PostMapping(value = "/upload", consumes = "multipart/form-data")
public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
long totalSize = file.getSize();
InputStream inputStream = file.getInputStream();
// Simulate progress reporting by reading chunks of data and updating the response.
byte[] buffer = new byte[8192];
int bytesRead;
long currentBytesRead = 0L;
while ((bytesRead = inputStream.read(buffer)) != -1) {
currentBytesRead += bytesRead;
float percentageComplete = (currentBytesRead * 100f / totalSize);
HttpServletResponse res = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
res.getWriter().write("{\"progress\": " + Math.round(percentageComplete) + "}");
res.getWriter().flush();
}
return ResponseEntity.ok("File uploaded successfully");
}
}
```
此段代码展示了如何创建一个简单的API接口以接受文件流输入的同时计算已完成的比例[^1]。
需要注意的是上述例子仅作示意用途;实际生产环境中应当考虑安全性措施如防止恶意攻击者利用大尺寸文件拖慢服务器响应速度等问题。
对于更复杂的场景,则建议引入专门的库比如Apache Commons IO或者第三方组件(例如Resumable.js)来进行更加精细的操作控制。
#### 前端实现方案
前端方面则需定期向服务器发送AJAX请求查询最新的百分比数值以便及时刷新UI界面。这里给出一段基于Vue.js框架下的简单实例:
```javascript
<template>
<div id="app">
<input type="file" @change="onFileChange"/>
<button v-on:click="submitForm">Submit</button>
<!-- Progress bar -->
<progress :value="progressValue" max="100"></progress>
</div>
</template>
<script>
export default {
name: 'App',
data() {
return {
selectedFile: null,
progressValue: 0
};
},
methods:{
onFileChange(event){
this.selectedFile=event.target.files[0];
},
submitForm(){
const formData=new FormData();
formData.append('file',this.selectedFile);
let xhr = new XMLHttpRequest();
xhr.open('POST','http://localhost:8080/api/file/upload');
xhr.upload.onprogress=function(e){
if(e.lengthComputable){
console.log(`Progress:${Math.floor((e.loaded/e.total)*100)}%`);
this.progressValue=Math.floor((e.loaded/e.total)*100); // Update UI here
}
}.bind(this);
xhr.send(formData);
}
}
};
</script>
```
这段脚本实现了当用户选择好要上传的图片之后点击提交按钮触发异步HTTP POST操作并向后台传递二进制资料的过程。与此同时还会持续监控整个过程中的字节数变化情况从而调整界面上进度指示器的位置[^2]。
阅读全文
相关推荐

















