利用commons-fileUpload显示进度的文件上传
时间: 2023-12-06 10:02:34 浏览: 43
要利用commons-fileUpload显示上传进度,可以使用ProgressListener接口和ProgressBar组件。
首先,创建一个类实现ProgressListener接口,该接口包含了上传进度的相关方法。例如:
```
public class UploadProgressListener implements ProgressListener {
private final HttpSession session;
public UploadProgressListener(HttpSession session) {
this.session = session;
ProgressEntity status = new ProgressEntity();
session.setAttribute("status", status);
}
@Override
public void update(long bytesRead, long contentLength, int items) {
ProgressEntity status = (ProgressEntity) session.getAttribute("status");
status.setBytesRead(bytesRead);
status.setContentLength(contentLength);
status.setItems(items);
}
}
```
然后,在上传文件时将该监听器添加到FileItemFactory中:
```
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setProgressListener(new UploadProgressListener(request.getSession()));
```
最后,在前端页面中使用ProgressBar组件显示上传进度,例如:
```
<progress id="progressbar" max="100"></progress>
<script>
setInterval(function() {
$.get("/upload/progress", function(data) {
$("#progressbar").val(data.percent);
});
}, 1000);
</script>
```
其中,/upload/progress是获取上传进度的接口。在该接口中,可以从session中获取上传进度的状态,计算出百分比并返回给前端。
这样,就可以实现上传进度的显示了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)