Angular4: How to recover values in Response Headers

Asked

Viewed 186 times

0

I have a Webservice that returns a PDF file (byte[]). I am returning the file name in the Response header.

In Chrome I can see the values of 'Response Headers' and see that all headers are there, including the file name. However, when I try to recover these values in Angular, I can’t, because in headers comes only the "Content-Type:application/pdf".

getPdf(url: string){

    this.http.get(url, {responseType: 'arraybuffer', observe:'response'})
        .subscribe(data => {
            console.log(data.headers.get('filename')); // Imprime: null
            console.log(data.headers.keys()); // Imprime: ["Content-Type"]
            this.downloadFile(data.body);
    });
  }

Response Headers displayed in browser:

Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:Origin, X-Request-Width, Content-Type, Accept, authCode
Access-Control-Allow-Origin:*
Connection:keep-alive
Content-Disposition:attachment; filename=arquivo.pdf
Content-Type:application/pdf
Date:Mon, 26 Nov 2018 14:23:37 GMT
filename:arquivo.pdf
Server:JBoss-EAP/7
Transfer-Encoding:chunked
X-Powered-By:Undertow/1

Does anyone know what is wrong? How do I recover this value?

  • Try it this way: data.headers.get('Content-Disposition').split(';')[1].trim().split('=')[1] if it works I’ll explain. I can’t test!

  • It doesn’t work like this because it is only getting the 'Content-Type' in headers.

1 answer

0

I discovered the problem. On the return of my service, I need to define the Headers I want exposed with the value 'Access-Control-Expose-Headers'. If not set this Angular ignores past values.

For example, my java webservice stayed:

protected Response buildFile(Status status, byte[] file, String nomeArquivo) {
        return Response.status(status)
                .entity(file)
                .header("Access-Control-Allow-Credentials", "true")
                .header("Access-Control-Expose-Headers", "Content-Disposition, filename")
                .header("Content-Type", "application/pdf")
                .header("Content-Disposition", "attachment; filename="+ nomeArquivo)
                .header("filename", nomeArquivo)
                .build();
    }

More information on: https://stackoverflow.com/questions/50044299/how-to-get-the-name-of-a-file-downloaded-with-angular5

  • After that your change the code I showed did not work?

  • No. I answered your comment there.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.