I have a WebApi / MVC app for which I am developing an angular2 client (to replace MVC). I am having some troubles understanding how Angular saves a file.
The request is ok (works fine with MVC, and we can log the data received) but I can't figure out how to save the downloaded data (I am mostly following the same logic as in this post). I am sure it is stupidly simple, but so far I am simply not grasping it.
The code of the component function is below. I've tried different alternatives, the blob way should be the way to go as far as I understood, but there is no function createObjectURL
in URL
. I can't even find the definition of URL
in window, but apparently it exists. If I use the FileSaver.js
module I get the same error. So I guess this is something that changed recently or is not yet implemented. How can I trigger the file save in A2?
downloadfile(type: string){
let thefile = {};
this.pservice.downloadfile(this.rundata.name, type)
.subscribe(data => thefile = new Blob([data], { type: "application/octet-stream" }), //console.log(data),
error => console.log("Error downloading the file."),
() => console.log('Completed file download.'));
let url = window.URL.createObjectURL(thefile);
window.open(url);
}
For the sake of completeness, the service that fetches the data is below, but the only thing it does is to issue the request and pass on the data without mapping if it succeeds:
downloadfile(runname: string, type: string){
return this.authHttp.get( this.files_api + this.title +"/"+ runname + "/?file="+ type)
.catch(this.logAndPassOn);
}
Download *.zip solution for angular 2.4.x: you must import ResponseContentType from '@angular/http' and change responseType to ResponseContentType.ArrayBuffer (by default it ResponseContentType.Json)
The problem is that the observable runs in another context, so when you try to create the URL var, you have an empty object and not the blob you want.
One of the many ways that exist to solve this is as follows:
When the request is ready it will call the function "downloadFile" that is defined as follows:
the blob has been created perfectly and so the URL var, if doesn't open the new window please check that you have already imported 'rxjs/Rx' ;
I hope this can help you.
I got a solution for downloading from angular 2 without getting corrupt, using spring mvc and angular 2
1st- my return type is :-ResponseEntity from java end. Here I am sending byte[] array has return type from the controller.
2nd- to include the filesaver in your workspace-in the index page as:
3rd- at component ts write this code:
This will give you xls file format. If you want other formats change the mediatype and file name with right extension.
If you don't need to add headers in the request, to download a file in Angular2 you can do a simple:
in your component.
How about this?
I could do with it.
no need additional package.
Simply put the
url
ashref
as below .