Reputation: 151
I'm trying to download a file that I send from my back end server. The get method works well on postman, but I can't make it work from my front-end app (angular 5).
Here's my back end:
@GET
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Path("/recupererDocument/{id}")
@ResponseStatus(value = {Response.Status.OK, Response.Status.BAD_REQUEST,
Response.Status.INTERNAL_SERVER_ERROR,})
@ElementClass(request = Long.class, response = Response.class)
public Response recupererDocument(
@NotNull(message = "L'id (identifiant du document) est obligatoire") @PathParam("id") final String id);
public Response recupererDocument(String id) {
File file = null;
final WebTarget target = ...;
Builder builderDoc = target.request(typeMime);
final Response reponseDocument = builderDoc.accept(typeMime).get();
LOGGER.debug(reponseDocument.getStatus());
if (reponseDocument.getStatus() == 200) {
file = reponseDocument.readEntity(new GenericType<File>() {
});
}
reponseDocument.close();
return Response.ok(file, MediaType.APPLICATION_OCTET_STREAM).build();
}
And my front-end:
telechargerPieceJointe(id: string): void {
this.s
.telechargerPieceJointe(id)
.then(pj => {
this.downloadFile(pj);
})
.catch(e => {
if (isDevMode()) {
console.log('Erreur : ' + e);
}
});
}
downloadFile(data: Response) {
const blob = new Blob([data], {type: 'application/octet-stream'});
const url = window.URL.createObjectURL(blob);
window.open(url);
}
telechargerPieceJointe(id: string): Promise<any> {
const url = environment.rest.local.recupererDocument + '/' + id;
const headers = new HttpHeaders({
Accept: 'application/pdf',
responseType: 'blob'
});
return this.httpClient.get(url, {headers}).toPromise();
}
Right now in my front end in debug I don't enter the ".then' method but the .catch.
I've the following message :
Unexpected token % in JSON at position 0.
But in the "network" tab in chrome dev tools the request is good (200), and I can see my object in the "response" part. I don't understand why it's not working :/.
If someone sees what I'm doing wrong it would probably save my sanity.
Upvotes: 1
Views: 2309
Reputation: 14109
Angular tries to parse your http response body as JSON (which is the default response type).
The responseType
isn't specified in the HttpHeaders
but in the httpOptions Object.
Specify responseType: 'blob'
in the httpOptions you pass to httpClient.get
.
telechargerPieceJointe(id: string): Observable<any> {
const url = environment.rest.local.recupererDocument + '/' + id;
const headers = new HttpHeaders({
Accept: 'application/pdf'
});
return this.httpClient.get(url, { headers, responseType: 'blob' });
}
Upvotes: 2