Angular下载大斑点 [英] Angular Download Large blobs
问题描述
我遇到的问题类似于这个人已成功通过HTTP GET下载了从后端生成的Blob,但但文件在下载开始之前已保存到浏览器内存中.
I have an issue similar to this one where I am successfully downloading a blob generated from a backend via HTTP GET but the file is being saved to browser memory before the download begins.
下载小文件时没有问题,但不会立即下载100mb +的文件.
There's no problem when downloading small files but it doesn't immediately download 100mb+ files.
订阅GET本身会导致保存大文件的延迟.
Subscribing to the GET itself is causing the delay of saving the large files.
我正在将Angular 6与对象存储后端一起使用.这是下载功能:
I'm using Angular 6 with an object store backend. Here's the download function:
finalDownload(url: string) {
let headers = new HttpHeaders();
headers = headers.append('X-Auth-Token', token);
return this.http.get(url, { headers, responseType: 'blob' })
.subscribe(response => {
saveAs(response);
})
}
流程如下:
- 用户点击下载按钮
- 带有标头的GET请求被触发到后端
- 我订阅响应后,该Blob就会存储在浏览器内存中.
- 将Blob完全存储在浏览器中后,将开始saveAs/下载
第3步是问题所在. 这个devtools屏幕快照传输了108 MB 累积到文件大小(我下载了100 mb文件)开始下载到文件系统之前.
Step 3 is where the issue is. This devtools screenshot with 108 MB transferred accumulates to the file size (I downloaded a 100 mb file) before the download itself to filesystem begins.
推荐答案
您可以尝试使用URL.createObjectURL:
You can try to use URL.createObjectURL:
URL.createObjectURL()可用于构造和解析URL.具体来说,URL.createObjectURL()可用于创建对文件或Blob的引用.与base64编码的数据URL相反,它不包含对象的实际数据,而是包含引用.
URL.createObjectURL() can be used to construct and parse URLs. URL.createObjectURL() specifically, can be used to create a reference to a File or a Blob. As opposed to a base64-encoded data URL, it doesn’t contain the actual data of the object – instead it holds a reference.
这件事的好处是它的速度非常快.以前,我们必须实例化FileReader实例,并将整个文件读取为base64数据URL,这需要时间和大量内存.使用createObjectURL(),可以立即获得结果,从而使我们可以执行将图像数据读取到画布的操作.
The nice thing about this is that it’s really fast. Previously, we’ve had to instantiate a FileReader instance and read the whole file as a base64 data URL, which takes time and a lot of memory. With createObjectURL(), the result is available straight away, allowing us to do things like reading image data to a canvas.
使用以下代码作为参考
const blob = new Blob([data], { type: 'application/octet-stream' });
this.fileUrl = this.sanitizer.bypassSecurityTrustResourceUrl(window.URL.createObjectURL(blob));
这篇关于Angular下载大斑点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!