I want to download files from angular 2. My problem is, that all files I get from the Spring REST API are twice file size.
Angular Snippet:
return this.authHttp.get(this.restAPI + '/downloadFile/' + fileId)
.toPromise()
.then(response => {
// var arrayBufferView = new Uint8Array( response.arrayBuffer() );
// var blob = new Blob( [ arrayBufferView ], { type: response.headers.get("Content-Type") } );
// return blob;
return new Blob([response.arrayBuffer()], { type: response.headers.get("Content-Type")})
})
.catch(this.handleError);
Spring REST Snippet:
@RequestMapping(value = "/downloadFile2/{fileId}",
method = RequestMethod.GET)
public void downloadFileHandler2(@RequestHeader("Authorization") String token,
@PathVariable String fileId, HttpServletResponse response) throws IOException {
changeToCustomerDataBase(token);
File file = projectService.readFromDB(fileId);
response.addHeader("Content-Disposition", "attachment; filename="+file.getName());
response.setContentType(Files.probeContentType(file.toPath()));
response.setContentLengthLong(file.length());
FileInputStream fis = new FileInputStream(file);
int c;
while((c = fis.read()) > -1) {
response.getOutputStream().write(c);
}
response.flushBuffer();
fis.close();
}
Files, thar coming from the database, have the original size.
What is wrong? Did I forget something? I'm very grateful for any help.
I had the same Problem yesterday and solved it. I hope you or anyone else can use the solution. Add responseType: ResponseContentType.Blob
to your requestOptions of the authHttp.get
you use.
let requestOptions: RequestOptionsArgs = {
...,
responseType: ResponseContentType.Blob
};
.
.
.
return this.http.request(path, requestOptions);
Then use response.blob()
instead of new Blob([response.arrayBuffer()], { type: response.headers.get("Content-Type")})
For me that worked. I hope it helps you too.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.