诉求
文件上传到oss,前端每间隔一段时间查询接口获取后端返回的进度,并在页面上按照百分比展示进度条,当达到百分比进度的时候下载文件
技术选型
后端:SpringBoot + Oss + Redis + Swagger3(参考前一篇文章:文件上传oss,并查询上传进度)
前端:JavaScript 实现(使用 JavaScript 定时器(例如 setInterval())每隔一段时间执行一次函数来查询后端接口。在函数中,使用 XMLHttpRequest 或 Fetch API 向后端发起请求,并在响应中获取百分比。然后,使用 JavaScript 将百分比应用到页面上的进度条元素,例如设置进度条元素的 width 属性为百分比。)
前端代码
<!DOCTYPE html> <html> <head> <title>Progress Bar Example</title> <style> .progress-container { width: 100%; height: 20px; background-color: #ddd; border-radius: 10px; } .progress-bar { width: 0%; height: 100%; background-color: #4CAF50; border-radius: 10px; transition: width 0.3s ease-in-out; } </style> </head> <body> <div class="progress-container"> <div id="progress-bar" class="progress-bar"></div> </div> <script> // Get the progress bar element const progressBar = document.getElementById('progress-bar'); // Call the function every 3 seconds var interval = setInterval(getProgress, 3000); //获取进度 function getProgress() { // Make a GET request to the backend endpoint fetch('http://localhost:8080/fileApi/simulateUploadedFile') .then(response => response.json()) .then(data => { // Update the progress bar width //此处后端返回逻辑需要修改,返回int类型的数值,如后端返回String类型的50%,可能识别不了,%放到前端处理就好了 progressBar.style.width = `${data.progress}%`; //当进度到达100下载文件 if (data === 100) { clearInterval(interval); downloadFile(); } }) .catch(error => { console.error('Error fetching progress:', error); }); } //下载文件 function downloadFile() { // Make a GET request to the backend endpoint to get the OSS URL of the file fetch('http://localhost:8080/fileApi/simulateUploadedFile') .then(response => response.json()) .then(data => { // Create a link element to trigger the browser to download the file var a = document.createElement('a'); a.href = data.data; a.download = 'file.zip'; a.click(); }) .catch(error => { console.error('Error fetching file url:', error); }); } </script> </body> </html>
逻辑分析
- 访问html时,到达间隔时间请求后端接口拿到进度信息
- 拿到进度信息后对进度条的长度进行更新
- 当进度条达到100%时,直接下载文件(下载文件这一步前端使用后端返回的oss地址即可)
注意点
此篇文章中后端所用到的进度查询,以及进度达到100%返回的文件名,需要对上面参考文章的返回结构进行修改
@Data public class ExportProgress implements Serializable { @ApiModelProperty("进度(百分比)") private Integer progress; @ApiModelProperty("导出内容:oss地址信息") private String data; @ApiModelProperty("信息,异常时往里面写入") private String msg; @ApiModelProperty("code信息:约定200为成功code,500为失败code") private String code; }
样例数据
{ "data": "http://xxx.oss-cn-hangzhou.aliyuncs.com/e1231ae3-54b8-4d25-a847-ef3f0452302c.xlsx", "progress": "100%", "code":200 }