Download a file using Angular 6 and Spring Rest API
up vote
0
down vote
favorite
I have a problem downloading a file from a rest api using angular 6
Back-end method
@RequestMapping(value = "/print/{id}")
public ResponseEntity<byte> generateReport(@PathVariable("id") long id_project){
Map<String, Object> mapper = new HashMap<String, Object>();
byte content = exportService.export(mapper, ReportUtils.testReport, ReportUtils.FileFormat.PDF.toString());
return new ResponseEntity<>(content, Utils.getPDFHeaders("Situation_test.pdf"), HttpStatus.OK);
}
Mathod getHeader
public static HttpHeaders getPDFHeaders(String fileName) {
HttpHeaders head = new HttpHeaders();
head.setContentType(MediaType.parseMediaType("application/pdf"));
head.add("content-disposition", "attachment; filename=" + fileName);
head.setContentDispositionFormData(fileName, fileName);
head.setCacheControl("must-revalidate, post-check=0, pre-check=0");
return head;
}
My Angular Service
download(url: string): any {
let headers = new HttpHeaders();
headers = headers.append('Authorization', 'Bearer ' + this.getToken());
this.http.get(this.API_URL + url, {headers: headers}).subscribe((res) => {
const file = new Blob([res], {
type: 'application/pdf',
});
const a = document.createElement('a');
a.href = this.API_URL + (<any>res)._body;
a.target = '_blank';
document.body.appendChild(a);
a.click();
return res;
}, error => {
let alert: any = {
title: 'Notify Title',
body: 'Notify Body',
};
alert.body = error.error.message || JSON.stringify(error.error);
alert.title = error.error.error;
alert = this.alertService.handleError(error);
alert.position = 'rightTop';
console.log(error);
this.alertService.notifyError(alert);
return error;
});
}
I have already tried my API using PostMan and it word perfectly but in Angular it give me this error
HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:8080/api/projects/print/1", ok: false, …}
error: {error: SyntaxError: Unexpected token % in JSON at position 0 at JSON.parse (<anonymous>) at XMLHttp…, text: "%PDF-1.4↵%����↵3 0 obj↵<</Filter/FlateDecode/Lengt…25f1>]/Root 8 0 R/Size 10>>↵startxref↵1049↵%%EOF↵"}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure during parsing for http://localhost:8080/api/projects/print/1"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
url: "http://localhost:8080/api/projects/print/1"
java spring angular
add a comment |
up vote
0
down vote
favorite
I have a problem downloading a file from a rest api using angular 6
Back-end method
@RequestMapping(value = "/print/{id}")
public ResponseEntity<byte> generateReport(@PathVariable("id") long id_project){
Map<String, Object> mapper = new HashMap<String, Object>();
byte content = exportService.export(mapper, ReportUtils.testReport, ReportUtils.FileFormat.PDF.toString());
return new ResponseEntity<>(content, Utils.getPDFHeaders("Situation_test.pdf"), HttpStatus.OK);
}
Mathod getHeader
public static HttpHeaders getPDFHeaders(String fileName) {
HttpHeaders head = new HttpHeaders();
head.setContentType(MediaType.parseMediaType("application/pdf"));
head.add("content-disposition", "attachment; filename=" + fileName);
head.setContentDispositionFormData(fileName, fileName);
head.setCacheControl("must-revalidate, post-check=0, pre-check=0");
return head;
}
My Angular Service
download(url: string): any {
let headers = new HttpHeaders();
headers = headers.append('Authorization', 'Bearer ' + this.getToken());
this.http.get(this.API_URL + url, {headers: headers}).subscribe((res) => {
const file = new Blob([res], {
type: 'application/pdf',
});
const a = document.createElement('a');
a.href = this.API_URL + (<any>res)._body;
a.target = '_blank';
document.body.appendChild(a);
a.click();
return res;
}, error => {
let alert: any = {
title: 'Notify Title',
body: 'Notify Body',
};
alert.body = error.error.message || JSON.stringify(error.error);
alert.title = error.error.error;
alert = this.alertService.handleError(error);
alert.position = 'rightTop';
console.log(error);
this.alertService.notifyError(alert);
return error;
});
}
I have already tried my API using PostMan and it word perfectly but in Angular it give me this error
HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:8080/api/projects/print/1", ok: false, …}
error: {error: SyntaxError: Unexpected token % in JSON at position 0 at JSON.parse (<anonymous>) at XMLHttp…, text: "%PDF-1.4↵%����↵3 0 obj↵<</Filter/FlateDecode/Lengt…25f1>]/Root 8 0 R/Size 10>>↵startxref↵1049↵%%EOF↵"}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure during parsing for http://localhost:8080/api/projects/print/1"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
url: "http://localhost:8080/api/projects/print/1"
java spring angular
AngularHttpClient
but default hascontent-type: application/json
and so expects json. If you want the pdf you will need to set it
– Mike Tung
Nov 13 at 15:35
add a comment |
up vote
0
down vote
favorite
up vote
0
down vote
favorite
I have a problem downloading a file from a rest api using angular 6
Back-end method
@RequestMapping(value = "/print/{id}")
public ResponseEntity<byte> generateReport(@PathVariable("id") long id_project){
Map<String, Object> mapper = new HashMap<String, Object>();
byte content = exportService.export(mapper, ReportUtils.testReport, ReportUtils.FileFormat.PDF.toString());
return new ResponseEntity<>(content, Utils.getPDFHeaders("Situation_test.pdf"), HttpStatus.OK);
}
Mathod getHeader
public static HttpHeaders getPDFHeaders(String fileName) {
HttpHeaders head = new HttpHeaders();
head.setContentType(MediaType.parseMediaType("application/pdf"));
head.add("content-disposition", "attachment; filename=" + fileName);
head.setContentDispositionFormData(fileName, fileName);
head.setCacheControl("must-revalidate, post-check=0, pre-check=0");
return head;
}
My Angular Service
download(url: string): any {
let headers = new HttpHeaders();
headers = headers.append('Authorization', 'Bearer ' + this.getToken());
this.http.get(this.API_URL + url, {headers: headers}).subscribe((res) => {
const file = new Blob([res], {
type: 'application/pdf',
});
const a = document.createElement('a');
a.href = this.API_URL + (<any>res)._body;
a.target = '_blank';
document.body.appendChild(a);
a.click();
return res;
}, error => {
let alert: any = {
title: 'Notify Title',
body: 'Notify Body',
};
alert.body = error.error.message || JSON.stringify(error.error);
alert.title = error.error.error;
alert = this.alertService.handleError(error);
alert.position = 'rightTop';
console.log(error);
this.alertService.notifyError(alert);
return error;
});
}
I have already tried my API using PostMan and it word perfectly but in Angular it give me this error
HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:8080/api/projects/print/1", ok: false, …}
error: {error: SyntaxError: Unexpected token % in JSON at position 0 at JSON.parse (<anonymous>) at XMLHttp…, text: "%PDF-1.4↵%����↵3 0 obj↵<</Filter/FlateDecode/Lengt…25f1>]/Root 8 0 R/Size 10>>↵startxref↵1049↵%%EOF↵"}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure during parsing for http://localhost:8080/api/projects/print/1"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
url: "http://localhost:8080/api/projects/print/1"
java spring angular
I have a problem downloading a file from a rest api using angular 6
Back-end method
@RequestMapping(value = "/print/{id}")
public ResponseEntity<byte> generateReport(@PathVariable("id") long id_project){
Map<String, Object> mapper = new HashMap<String, Object>();
byte content = exportService.export(mapper, ReportUtils.testReport, ReportUtils.FileFormat.PDF.toString());
return new ResponseEntity<>(content, Utils.getPDFHeaders("Situation_test.pdf"), HttpStatus.OK);
}
Mathod getHeader
public static HttpHeaders getPDFHeaders(String fileName) {
HttpHeaders head = new HttpHeaders();
head.setContentType(MediaType.parseMediaType("application/pdf"));
head.add("content-disposition", "attachment; filename=" + fileName);
head.setContentDispositionFormData(fileName, fileName);
head.setCacheControl("must-revalidate, post-check=0, pre-check=0");
return head;
}
My Angular Service
download(url: string): any {
let headers = new HttpHeaders();
headers = headers.append('Authorization', 'Bearer ' + this.getToken());
this.http.get(this.API_URL + url, {headers: headers}).subscribe((res) => {
const file = new Blob([res], {
type: 'application/pdf',
});
const a = document.createElement('a');
a.href = this.API_URL + (<any>res)._body;
a.target = '_blank';
document.body.appendChild(a);
a.click();
return res;
}, error => {
let alert: any = {
title: 'Notify Title',
body: 'Notify Body',
};
alert.body = error.error.message || JSON.stringify(error.error);
alert.title = error.error.error;
alert = this.alertService.handleError(error);
alert.position = 'rightTop';
console.log(error);
this.alertService.notifyError(alert);
return error;
});
}
I have already tried my API using PostMan and it word perfectly but in Angular it give me this error
HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:8080/api/projects/print/1", ok: false, …}
error: {error: SyntaxError: Unexpected token % in JSON at position 0 at JSON.parse (<anonymous>) at XMLHttp…, text: "%PDF-1.4↵%����↵3 0 obj↵<</Filter/FlateDecode/Lengt…25f1>]/Root 8 0 R/Size 10>>↵startxref↵1049↵%%EOF↵"}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure during parsing for http://localhost:8080/api/projects/print/1"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
url: "http://localhost:8080/api/projects/print/1"
java spring angular
java spring angular
asked Nov 13 at 15:33
Ayoub EL Abassi
216
216
AngularHttpClient
but default hascontent-type: application/json
and so expects json. If you want the pdf you will need to set it
– Mike Tung
Nov 13 at 15:35
add a comment |
AngularHttpClient
but default hascontent-type: application/json
and so expects json. If you want the pdf you will need to set it
– Mike Tung
Nov 13 at 15:35
Angular
HttpClient
but default has content-type: application/json
and so expects json. If you want the pdf you will need to set it– Mike Tung
Nov 13 at 15:35
Angular
HttpClient
but default has content-type: application/json
and so expects json. If you want the pdf you will need to set it– Mike Tung
Nov 13 at 15:35
add a comment |
1 Answer
1
active
oldest
votes
up vote
0
down vote
accepted
Try adding content-type to your request headers.
You can try this as an exemple:
let headers = new Headers({'Content-Type': 'application/pdf', 'Accept': 'application/pdf'});
the problem is that i have many types of files so what do you think the solution is
– Ayoub EL Abassi
Nov 13 at 19:08
In this case, you can use octet-stream. In your backend, you will have something like this : head.setContentType(MediaType.APPLICATION_OCTET_STREAM); In your frontend, specify the Content-Type in your header const headers = new HttpHeaders({'Content-Type': 'application/octet-stream'}); And in your Blob object too : const file = new Blob([res], { type: 'octet-stream', }); You may wanna have a look at downloadjs which helps you downloading files easily
– gladiatoriitoo
Nov 14 at 9:47
thank you very much that was very helpful it worked very well
– Ayoub EL Abassi
Nov 15 at 11:49
You are welcome
– gladiatoriitoo
Nov 16 at 10:40
add a comment |
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
0
down vote
accepted
Try adding content-type to your request headers.
You can try this as an exemple:
let headers = new Headers({'Content-Type': 'application/pdf', 'Accept': 'application/pdf'});
the problem is that i have many types of files so what do you think the solution is
– Ayoub EL Abassi
Nov 13 at 19:08
In this case, you can use octet-stream. In your backend, you will have something like this : head.setContentType(MediaType.APPLICATION_OCTET_STREAM); In your frontend, specify the Content-Type in your header const headers = new HttpHeaders({'Content-Type': 'application/octet-stream'}); And in your Blob object too : const file = new Blob([res], { type: 'octet-stream', }); You may wanna have a look at downloadjs which helps you downloading files easily
– gladiatoriitoo
Nov 14 at 9:47
thank you very much that was very helpful it worked very well
– Ayoub EL Abassi
Nov 15 at 11:49
You are welcome
– gladiatoriitoo
Nov 16 at 10:40
add a comment |
up vote
0
down vote
accepted
Try adding content-type to your request headers.
You can try this as an exemple:
let headers = new Headers({'Content-Type': 'application/pdf', 'Accept': 'application/pdf'});
the problem is that i have many types of files so what do you think the solution is
– Ayoub EL Abassi
Nov 13 at 19:08
In this case, you can use octet-stream. In your backend, you will have something like this : head.setContentType(MediaType.APPLICATION_OCTET_STREAM); In your frontend, specify the Content-Type in your header const headers = new HttpHeaders({'Content-Type': 'application/octet-stream'}); And in your Blob object too : const file = new Blob([res], { type: 'octet-stream', }); You may wanna have a look at downloadjs which helps you downloading files easily
– gladiatoriitoo
Nov 14 at 9:47
thank you very much that was very helpful it worked very well
– Ayoub EL Abassi
Nov 15 at 11:49
You are welcome
– gladiatoriitoo
Nov 16 at 10:40
add a comment |
up vote
0
down vote
accepted
up vote
0
down vote
accepted
Try adding content-type to your request headers.
You can try this as an exemple:
let headers = new Headers({'Content-Type': 'application/pdf', 'Accept': 'application/pdf'});
Try adding content-type to your request headers.
You can try this as an exemple:
let headers = new Headers({'Content-Type': 'application/pdf', 'Accept': 'application/pdf'});
edited Nov 14 at 9:06
answered Nov 13 at 16:22
gladiatoriitoo
182
182
the problem is that i have many types of files so what do you think the solution is
– Ayoub EL Abassi
Nov 13 at 19:08
In this case, you can use octet-stream. In your backend, you will have something like this : head.setContentType(MediaType.APPLICATION_OCTET_STREAM); In your frontend, specify the Content-Type in your header const headers = new HttpHeaders({'Content-Type': 'application/octet-stream'}); And in your Blob object too : const file = new Blob([res], { type: 'octet-stream', }); You may wanna have a look at downloadjs which helps you downloading files easily
– gladiatoriitoo
Nov 14 at 9:47
thank you very much that was very helpful it worked very well
– Ayoub EL Abassi
Nov 15 at 11:49
You are welcome
– gladiatoriitoo
Nov 16 at 10:40
add a comment |
the problem is that i have many types of files so what do you think the solution is
– Ayoub EL Abassi
Nov 13 at 19:08
In this case, you can use octet-stream. In your backend, you will have something like this : head.setContentType(MediaType.APPLICATION_OCTET_STREAM); In your frontend, specify the Content-Type in your header const headers = new HttpHeaders({'Content-Type': 'application/octet-stream'}); And in your Blob object too : const file = new Blob([res], { type: 'octet-stream', }); You may wanna have a look at downloadjs which helps you downloading files easily
– gladiatoriitoo
Nov 14 at 9:47
thank you very much that was very helpful it worked very well
– Ayoub EL Abassi
Nov 15 at 11:49
You are welcome
– gladiatoriitoo
Nov 16 at 10:40
the problem is that i have many types of files so what do you think the solution is
– Ayoub EL Abassi
Nov 13 at 19:08
the problem is that i have many types of files so what do you think the solution is
– Ayoub EL Abassi
Nov 13 at 19:08
In this case, you can use octet-stream. In your backend, you will have something like this : head.setContentType(MediaType.APPLICATION_OCTET_STREAM); In your frontend, specify the Content-Type in your header const headers = new HttpHeaders({'Content-Type': 'application/octet-stream'}); And in your Blob object too : const file = new Blob([res], { type: 'octet-stream', }); You may wanna have a look at downloadjs which helps you downloading files easily
– gladiatoriitoo
Nov 14 at 9:47
In this case, you can use octet-stream. In your backend, you will have something like this : head.setContentType(MediaType.APPLICATION_OCTET_STREAM); In your frontend, specify the Content-Type in your header const headers = new HttpHeaders({'Content-Type': 'application/octet-stream'}); And in your Blob object too : const file = new Blob([res], { type: 'octet-stream', }); You may wanna have a look at downloadjs which helps you downloading files easily
– gladiatoriitoo
Nov 14 at 9:47
thank you very much that was very helpful it worked very well
– Ayoub EL Abassi
Nov 15 at 11:49
thank you very much that was very helpful it worked very well
– Ayoub EL Abassi
Nov 15 at 11:49
You are welcome
– gladiatoriitoo
Nov 16 at 10:40
You are welcome
– gladiatoriitoo
Nov 16 at 10:40
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53284400%2fdownload-a-file-using-angular-6-and-spring-rest-api%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Angular
HttpClient
but default hascontent-type: application/json
and so expects json. If you want the pdf you will need to set it– Mike Tung
Nov 13 at 15:35