提问人:James A Cubeta 提问时间:8/11/2022 最后编辑:James A Cubeta 更新时间:8/13/2022 访问量:462
Angular:下载“较大”文件时浏览器崩溃
Angular: browser crashes when downloading 'larger' files
问:
我在尝试通过我的 Angular (v11) Web 应用程序实现基于 Spring Boot 的服务器提供的电子表格下载时遇到了问题。我的应用程序提供了一些“更大”的电子表格供下载 (~32 MB),浏览器有时会在尝试下载这些文件时崩溃。
这是我的代码的基础知识 - 首先是我的 Angular 应用程序中的 RESTful 客户端:
export class RestService {
private url: string = "http://example.com/api/dowwnload";
constructor(private http: HttpClient) {}
requestFile(id: number): Observable<HttpResponse<any>> {
this.http.get<any>(url+"?id="+id, {observe: 'response', responseType: 'blob' as 'json'});
}
}
...以及尝试进行下载的代码(使用文件保护程序):
this.restService.requestFile(id).subscribe(res => {
// requires: import {saveAs} from 'file-saver';
saveAs(res.body, 'filename.xlxs');
});
下面是服务器端的终结点:
@GetMapping("/download")
public ResponseEntity<Resource> downloadFile(@RequestParam("id") int id) {
File out = exportFileToTmpById(id); // method that writes file to /tmp here
try {
FileSystemResource resource = new FileSystemResource(out);
HttpHeaders headers = new HttpHeaders();
headers.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + out.getName() + "\"");
return ResponseEntity.ok()
.headers(httpHeaders)
.contentLength(out.length())
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(resource);
}
catch (Exception e) {
e.printStackTrace();
}
}
我的直觉是,Angular 方面要么存在内存问题,要么存在竞争条件,但我不是这方面的专家(#programmingbystackoverflow)。浏览器(Chrome 和 Firefox)死机时没有错误消息,也没有相关消息写入 Chrome 的日志。我应该在单击后删除子元素“a”吗?
如果您需要更多详细信息,请告诉我,以帮助我解决此问题。
答:
0赞
James A Cubeta
8/13/2022
#1
多亏了@CuriousMind,通过 HttpClient 删除我的 REST 调用并使用锚标记直接调用端点非常适合我的目的:
const a = document.createElement('a');
a.setAttribute('display', 'none');
a.href = downloadServiceUrl+"?id="+id";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
不知道为什么会这样,但它确实有效。
另外,我注意到浏览器/应用程序在下载较大文件时会暂时冻结。也许网络工作者可以减轻这种副作用。
评论
0赞
CuriousMind
8/13/2022
棒。在我看来,问题似乎是别的什么。Web Worker 无法解决此问题。可能的罪魁祸首可能是防病毒软件、浏览器扩展程序,或者您正在 localhost 中运行可能正在消耗内存的应用程序。但同样,这些都是猜测。
上一个:如何访问原始图像数据
评论