How to download a zip file exposed by a JAX-RS resource and serve it to the user with Angular2 final?
Given a JAX-RS resource as:
@Produces({MediaType.APPLICATION_JSON})
@Consumes({MediaType.APPLICATION_JSON})
@Path("/myresource")
public class MyResource {
@Inject
MyFacade myFacade;
@POST
@Path("/download")
@Produces({"application/zip"})
public Response download(@NotNull Request req) {
byte[] zipFileContent = myFacade.download(req);
return Response
.ok(zipFileContent)
.type("application/zip")
.header("Content-Disposition", "attachment; filename = \"project.zip\"")
.build();
}
}
In order to consume and serve the file to an end user using a Angular2 application, we can use a service as:
...//other import statements
import fileSaver = require("file-saver");
@Injectable()
export class AngularService {
constructor(private http: Http) {
}
download(model: MyModel) {
this.http.post(BASE_URL + "myresource/download", JSON.stringify(model), {
method: RequestMethod.Post,
responseType: ResponseContentType.Blob,
headers: new Headers({'Content-type': 'application/json'})
}).subscribe(
(response) => {
var blob = new Blob([response.blob()], {type: 'application/zip'});
var filename = 'file.zip';
fileSaver.saveAs(blob, filename);
}
);
}
For this to work the fileSaver
should be imported in package.json
as:
"dependencies": {
// all angular2 dependencies...
"file-saver": "1.3.2"
},
And that service can be now injected on any component that requires access to the download
method