Reputation: 3192
i am using angular 2/4 for one of my projects and i am in a situation where i have to download a file on submitting the request. I am doing currently.
this._http.post('url', body, { headers: urlEncodedHeader, observe: 'response', responseType: 'arraybuffer' })
.subscribe((data) => {
let blob = new Blob([data.body], { 'type': 'application/octet-stream' });
saveAs(blob, 'file.zip');
})
The file size could be very huge so i want the browser to handle the request instead of parsing the data and creating a blob in the application side. So i read somewhere that we can create a form element dynamically and give the handle to the browser instead of letting the application handle the blob and storing in the memory. So i tried
post_to_url(path, params, method) {
method = method || "post";
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
for (var key in params) {
if (params.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("token", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
}
This doesnt seem to be working, the page always redirects to some error page. So my query is, how to download a huge file without hanging the browser. Please help.
Upvotes: 1
Views: 187
Reputation: 3192
The problem was i was doing
hiddenField.setAttribute("token", key);
instead of
hiddenField.setAttribute("name", key);
Changing to the name solved my issue
Upvotes: 1
Reputation: 4788
Maybe simply generate link to downloading file on post
:
this._http.post('url', body, { headers: urlEncodedHeader, observe: 'response', responseType: 'arraybuffer' })
.subscribe((data) => {
let link = data.body; // //http://path/to/file;
window.open(link);
// or
var link = document.createElement('a');
link.href = link
link.click();
});
Upvotes: 0