Reputation: 3842
I am trying to download a zip fie which is returned as binary in the response of a AJAX Request.
I tried the following code but was not able to download it and even if I downloaded it the file got corrupted. I checked whether the response is correct and went to the network tab in developer tool and saved the response as a zip file and opened it, and it was successfully opened. Hopefully someone can tell me what I am doing wrong.
var URL = window.URL;
var downloadData = new Blob([data._body], { type: 'application/octet-stream' });
var downloadURL = URL.createObjectURL(downloadData);
window.open(downloadURL);
the browser openes up a new window and tells me the file is not supported in IE & downloads a corrupted file in Chrome. The URL in browser is something like
blob:http://localhost:4200/62b8283c-1391-4133-98a4-ed3cc9aa1f73
-
var downloadData = new Blob([data._body], { type: 'application/zip' });
FileSaver.saveAs(downloadData,"hi.zip");
The above code does not give any specific errors but when the file is saved it is corrupted.
I also tried the above code with type as application/octet-stream
but that has the same result.
Thing is the binary data seems to be perfectly fine, the only thing I need to do is open a save dialog which will save the binary data. Seems to be a pretty simple usecase, but seems to be a bit confusing in case of zip in the Js/TS side. I think the main issue is that I am creating a blob with the binary data(which I don't think I need to or should be transforming to a blob) but I was not able to trigger the download without creating a blob object as the APIs seem to be accepting only blob(like the URL Object or FileSaver API).
Upvotes: 1
Views: 2242
Reputation: 188
I had the exact same problem, the zip file was corrupt when I was trying to open it. I fixed it by adding: responseType = ResponseContentType.ArrayBuffer
Here is my code:
public httpRequest(call) {
call.headers = new Headers({
'Authorization': 'Bearer ' + localStorage.getItem('id_token'),
'Content-Type': 'application/json',
'Accept': 'application/octet-stream'
});
let req = new Request(call);
req.responseType = ResponseContentType.ArrayBuffer;
return this.http.request(req).map((res: Response) => {
return res;
});
}
make sure you imported:
import { Http, Headers, Request, Response, BaseResponseOptions, ResponseContentType } from '@angular/http';
Upvotes: 2