My response Headers is:
HTTP/1.1 200 OK
Content-Disposition: attachment; filename="file.docx"
Accept-Ranges: bytes
Cache-Control: public, max-age=0
Last-Modified: Thu, 26 Apr 2018 10:37:00 GMT
ETag: W/"c61-16301871843"
Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document
Content-Length: 3169
Date: Thu, 26 Apr 2018 10:37:00 GMT
Connection: keep-alive
I tried this code,
public download(id: string): Observable<Blob> {
let headers = new Headers();
const _baseUrl = (Api.getUrl(Api.URLS.download));
headers.append('x-access-token', this.auth.getCurrentUser().token);
headers.append('sale_id', id);
return this.http.get(_baseUrl, { headers: headers, responseType: ResponseContentType.Blob})
.map((res) => {
console.log(res.headers) // show like in image
return new Blob([res.blob()], { type: 'application/octet-stream' })
});
}
that show in console:
Didn't show Content-Disposition !!
How do I get the name of the file from the headers?
Hope this will save your time,
First import file-saver to your components.ts file
import { saveAs } from 'file-saver';
return this.http.get(url, { headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
}, responseType: 'blob', observe: 'response' })
.pipe().subscribe({
next: (response: any) => {
let fileName = 'file';
const contentDisposition = response.headers.get('Content-Disposition');
if (contentDisposition) {
const fileNameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
const matches = fileNameRegex.exec(contentDisposition);
if (matches != null && matches[1]) {
fileName = matches[1].replace(/['"]/g, '');
}
}
const fileContent = response.body;
const blob = new Blob([fileContent], { type: 'application/octet-stream' });
saveAs(blob, fileName);
},
error: (error) => {
this.handleError(error);
}
});
Also, set API side header like
'Access-Control-Expose-Headers', 'Content-Disposition'
Your backend needs to return a specific header, Access-Control-Expose-Headers
. If you don't, Angular doesn't expose the header, explaining why you can't see it.
You can find more information here (although it's a bit old) and even more information here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With