java 用户在前端调用后端接口 下载文件到本机,并显示进度条
时间: 2024-03-14 19:43:47 浏览: 168
struts2实现文件上传显示进度条效果
您可以使用Spring Boot和Servlet技术实现在前端调用后端接口下载文件,并且利用JavaScript实现进度条的展示。
以下是一个代码示例:
1. 后端代码
```java
@RestController
public class FileDownloadController {
@GetMapping("/download")
public void downloadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
String fileName = "your_file_name";
String fileUrl = "your_file_url";
URL url = new URL(fileUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置请求方式
conn.setRequestMethod("GET");
// 设置连接超时时间
conn.setConnectTimeout(5000);
// 设置读取超时时间
conn.setReadTimeout(5000);
// 设置请求头信息
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3");
// 获取文件总长度
int contentLength = conn.getContentLength();
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
response.setHeader("Content-Length", String.valueOf(contentLength));
InputStream inputStream = conn.getInputStream();
OutputStream outputStream = response.getOutputStream();
byte[] buffer = new byte[1024];
int bytesRead = 0;
long bytesReadSum = 0;
while ((bytesRead = inputStream.read(buffer)) != -1) {
bytesReadSum += bytesRead;
// 计算下载进度
int progress = (int) (bytesReadSum * 100 / contentLength);
// 将下载进度写入response的header中,前端通过Header可以获取到下载进度
response.setHeader("X-Download-Progress", String.valueOf(progress));
outputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outputStream.close();
}
}
```
在代码中,您需要修改以下参数:
- fileName: 下载到本地的文件名称。
- fileUrl: 下载文件的URL地址。
在代码中,将下载进度通过Header的X-Download-Progress写入response中,前端可以通过获取Header中的X-Download-Progress来获取下载进度。
2. 前端代码
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File Download Example</title>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#download-button").click(function () {
var url = "/download";
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.onload = function (e) {
if (this.status == 200) {
var blob = this.response;
var fileName = "your_file_name";
var a = document.createElement('a');
a.download = fileName;
a.href = window.URL.createObjectURL(blob);
$("body").append(a);
a.click();
$(a).remove();
}
};
xhr.onprogress = function (e) {
if (e.lengthComputable) {
var progress = parseInt(e.loaded / e.total * 100);
$("#download-progress").text("Download Progress: " + progress + "%");
}
};
xhr.send();
});
});
</script>
</head>
<body>
<button id="download-button">Download File</button>
<div id="download-progress"></div>
</body>
</html>
```
在代码中,通过jQuery实现按钮的点击事件,并通过XMLHttpRequest发送GET请求,获取到文件流并下载到本地。同时,通过onprogress事件计算下载进度,并将进度显示在页面上。
注意:在实现前端下载文件时,需要将响应的Content-Type设置为application/octet-stream,并且设置Content-Disposition为attachment,这样浏览器就会弹出下载对话框。
阅读全文