0

I am using a Spring Boot backend and an Angular frontend and want to implement the functionality of downloading a pdf file.

For this purpose, I have implemented the following handler in my REST-controller:

  @GetMapping("/{id}")
  public ResponseEntity<Resource> getPdf(@PathVariable Long id) {
    Pdf pdf = this.pdfService.getPdf(id);
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.add("filename", pdf.getId());
    httpHeaders.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + pdf.getId() + "\"");
    return ResponseEntity.ok()
      .headers(httpHeaders)
      .body(new ByteArrayResource(pdf.getContent()));
  }

In my frontend, I am using file-saver to save the file after receiving the response from my backend. File-saver requires a file name, which I want to set by reading the filename from the http response header. The problem is that the header, which I have clearly set in my backend, is not visible in my client. When logging the response, I can only see the following headers:

response headers

I have no clue why I cannot see the header I have set in my backend.

After doing some research, I found out that maybe, just maybe, it has something to do with an access-control-allow-origin option I would need to set for custom Http headers. I played around with it, but didn't manage to come up with a solution.

So I am asking: Has anyone seen this problem before?

Luk
  • 1,009
  • 2
  • 15
  • 33

1 Answers1

1

most likely there are headers in the response, however you can not read them from JS for CORS security reasons.

you should add Access-Control-Expose-Headers header to expose these headers explicitly

Andrei
  • 10,117
  • 13
  • 21
  • Hi Andrei, thx so much for you help! I have added the following header to my GET-handler: `httpHeaders.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, "filename");`. Now, this solves the problem! Can you maybe explain why I have to do this? My REST-controller is annotated with `CrossOrigin('*')`, which I thought should be enough. Furthermore, even though I have the Spring Security dependency installted atm, I have disabled cors in my configuration. – Luk Aug 26 '22 at 10:41
  • it seems then if you want to use these headers across the app, you should explicitly list them in the CORS (global or local) configuration. they aren't handled automatically. – Andrei Aug 26 '22 at 10:52