danialfarid / ng-file-upload

Lightweight Angular directive to upload files with optional FileAPI shim for cross browser support
MIT License
7.87k stars 1.6k forks source link

How to get the response header? #1980

Open Natasha023 opened 7 years ago

Natasha023 commented 7 years ago

Hi there,

I an using the API call to download file. I want to get the response headers which include the file name(from Content-Disposition) and save the file with the exactly name that server returns.

Here is the piece of my code:

private fileUpload(method, path, data: any = false, params?: JSONAPIParams, headers?: any, responseType?: string){ return this.Upload.upload({ method: method, url: this.Env.config.apiHost + path, params: params, withCredentials: true, // required otherwise cookies are not sent headers: this.headers(headers), // headers param will override defaults data: data, responseType: responseType, }).then((response: any): any => { return response.data; }) .catch((reason: any) => { this.$log.error(API request failed for ${ method } /${ path }); this.$log.error(reason); return this.$q.reject(reason); }); }

How can I get the response header?

securityvoid commented 6 years ago

I have the same issue. To be even more specific.

The "response" object has response.headers() which is an array of the headers. However, this is not populated with a header named "content-disposition", even when I can see from a proxy that the server is properly returning that header.

I would like to get this value so that when I do a: FileSaver.saveAs(blob, fileName);

I can have the "fileName" value be the Content-Disposition value.

securityvoid commented 6 years ago

I figured this out, but this may be something worthy of an example being put together :-).

So my problem was CORS. I needed my backend API server to return a header: Access-Control-Expose-Header":"Content-Disposition

Once this header is set, I can access the Content-Disposition header with: response.headers()['content-disposition'];

I still have to parse it for the filename. However, even that someone covered here: https://stackoverflow.com/questions/33046930/how-to-get-the-name-of-a-file-downloaded-with-angular-http

To allow me to be a little lazy :-).