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"









share|improve this question






















  • 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















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"









share|improve this question






















  • 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













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"









share|improve this question













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






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 13 at 15:33









Ayoub EL Abassi

216




216












  • 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
















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












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'});





share|improve this answer























  • 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











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















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

























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'});





share|improve this answer























  • 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















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'});





share|improve this answer























  • 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













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'});





share|improve this answer














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'});






share|improve this answer














share|improve this answer



share|improve this answer








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


















  • 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


















draft saved

draft discarded




















































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.




draft saved


draft discarded














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





















































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







Popular posts from this blog

How to change which sound is reproduced for terminal bell?

Can I use Tabulator js library in my java Spring + Thymeleaf project?

Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents