I have a situation where I want to download a large file from my RestFul java backend.
The java backend will stream the file in chunks see following code:
String filePath = this.workProgressService.getFilePath(entityId);
Path path = Paths.get(filePath);
FileNameMap fileNameMap = URLConnection.getFileNameMap();
String mimeType = fileNameMap.getContentTypeFor(path.getFileName().toString());
if (mimeType == null) {
mimeType = "application/octet-stream";
}
response.setContentType(mimeType);
response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", path.getFileName().toString()));
FileCopyUtils.copy(Files.newInputStream(path), response.getOutputStream());
The service is working fine. F.E. when I go in the browser to my restendpoint http://localhost:8080/download a file window popup and I can download the file.
But when I do this from angular with the following code:
const options = new RequestOptions({responseType: ResponseContentType.Blob});
return this.authHttp.get(this.configurationService.getApiURL() + '/filedownload', options)
.map(response => {
console.log(response.blob());
});
The console log of the blob is triggered at the end when the file is completely downloaded. If I watch the request in the developer console of Chrome I can see it download the whole file first before it will log it's response. This way the file save dialog is not opened untill the response is there.
The problem is I can't just use a href to the location of the Rest endpoint because I need to send an authorization header in the GET request.
How can I solve this that the user can download the file with a dialog from the back-end directly and not have to wait till browser has completely downloaded the file?
解决方案
The problem is solved.
The GET request of angular will trigger the filesaver dialog when the whole get request is completed. When downloading a large file this is not ideal because it will be downloaded in the browsers memory.
Because I have to use an authorization token which normally is in the header I had to create a workaround.
The workaround is indeed using the window.location.href with the RESTful endpoint to download. But before going to this endpoint the restful backend is called to create a short to live token which is valid to download a file.
This token is appended to the URL for the location.href.
Now the browser handles the file dialog to save the file on the computer.