当我请求获取下载zip文件的webservice时,它会在不知不觉中下载文件内容,突然间,该文件就会以已完成下载(100%)的状态出现在下载任务栏中。
使用以下Angular方法:
const endpoint = "http://localhost:8080/download/zip"
this.http.get<Blop>(endpoint, {headers: httpHeaders, responseType: 'blob', reportProgress: true })
这里是我的订阅方法:
this.http.get<Blop>(endpoint, {headers: httpHeaders, responseType: 'blob', reportProgress: true }).subscribe({
next: data => {
console.log('blocking or not');
const blob = new Blob([data as any], { type: 'application/zip' });
window.location.href = URL.createObjectURL(blob);
}
})
我注意到我的console.log(...)
直到下载结束后才被调用,因此我认为浏览器界面无法检测到下载进度,直到达到window.location.href
。
如何强制在传输结束之前在下载任务栏中显示下载并在浏览器中监视下载进度?我找不到与异步块或类似内容相关的任何信息。
附注:我的后端正在提供数据流,所以后端不是问题。当直接通过浏览器调用我的API时,我们可以在下载任务栏中看到下载进度。但如果您们有兴趣的话,以下是片段(Spring-Boot):
@GetMapping("/download/zip")
fun download(response: HttpServletResponse): StreamingResponseBody {
val file = downloads.download("launcher")
response.contentType = "application/zip"
response.setHeader(
"Content-Disposition",
"attachment;filename=sample.zip"
)
response.setContentLengthLong(file.length())
return StreamingResponseBody { outputStream: OutputStream ->
var bytesRead: Int
val buffer = ByteArray(2048)
val inputStream: InputStream = file.inputStream()
while (inputStream.read(buffer).also { bytesRead = it } != -1) {
outputStream.write(buffer, 0, bytesRead)
}
}
}