Reputation: 32400
I've written code that uses Angular $http to download a file. The name of the file is not specified in the URL. The URL contains a unique identifier for the file, which is fetched from outside the application.
When $http.get(myUrl)
is called, everything works fine; the file is retrieved and I can access it in my callback handler, but I can't see how to get the name of the file. Capturing the raw response with Fiddler, I see this:
HTTP/1.1 200 OK
Cache-Control: private
Content-Length: 54
Content-Type: application/octet-stream
Server: Microsoft-IIS/8.5
Access-Control-Allow-Origin: http://www.example.com/getFile/12345
Access-Control-Allow-Credentials: true
Content-Disposition: attachment; filename=testfile.txt
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Fri, 09 Oct 2015 20:25:49 GMT
Lorem ipsum dolar sit amet! The contents of my file!
From the above, it is clear that the server is sending back the name of the file in the "Content-Disposition", but I haven't found anyway to access it within my Angular callback. How do I get the name of the file from the headers?
Edit in response to answer below:
I should have mentioned before that I already tried response.headers()
. It returns Object {content-type: "application/octet-stream", cache-control: "private"}
, so I still don't get Content-Disposition for some reason. response.headers('Content-Disposition')
returns null
.
Upvotes: 36
Views: 62738
Reputation: 99
(file gets saved in binary format in the browser. the filename is in client's Network/header/Content-Disposition, we need to fetch the filename)
In Server-side code:
node js code-
response.setHeader('Access-Control-Expose-Headers','Content-Disposition');
response.download(outputpath,fileName);
In client-side code:
1)appComponent.ts file
import { HttpHeaders } from '@angular/common/http';
this.reportscomponentservice.getReportsDownload(this.myArr).subscribe((event: any) => {
var contentDispositionData= event.headers.get('content-disposition');
let filename = contentDispositionData.split(";")[1].split("=")[1].split('"')[1].trim()
saveAs(event.body, filename);
});
2) service.ts file
import { HttpClient, HttpResponse } from '@angular/common/http';
getReportsDownload(myArr): Observable<HttpResponse<Blob>> {
console.log('Service Page', myArr);
return this.http.post(PowerSimEndPoints.GET_DOWNLOAD_DATA.PROD, myArr, {
observe: 'response',
responseType: 'blob'
});
}
Upvotes: 0
Reputation: 860
Many answers here and in another thread solve OP's specific case or are even more general. I believe that you should start with parse
function from content-disposition
npm package. But since I failed to make this package work in my Angular 12 app (even with attempts analogous to this comment), and other answers here don't satisfy my cases, I've created yet another function.
My flag case of a filename is Tyłe;k Mopka.png
, that results in a valid response header:
content-disposition: attachment; filename="Ty_ek; Mopka.png"; filename*=UTF-8''Ty%C5%82ek%3B%20Mopka.png
We've got here: a non ISO-8859-1 character, a space, a semicolon. The last one is especially interesting, not only because of parameters splitting, but also because of percent encoding (decodeURI
is not enough, we need to unescape
it).
export function parseContentDispositionFilename(contentDisposition: string): string {
const filename = getFilename(contentDisposition);
if (filename) {
return unescape(decodeURI(filename));
}
else {
throw new Error('content-disposition filename cannot be empty');
}
}
function getFilename(contentDisposition: string): string | undefined {
const filenames = getFilenameParams(contentDisposition);
if (filenames.filenamestar) {
// RFC 6266 4.1 filename* -> RFC 5987 3.2.1 ext-value
return filenames.filenamestar.replace(/^(?<charset>.+)'(?<language>.*)'(?<filename>.+)$/, '$<filename>');
}
else if (filenames.filename) {
// RFC 6266 4.1 filename (possibly quoted)
return filenames.filename.replace(/^"(?<filename>.+)"$/, '$<filename>');
}
else {
return undefined;
}
}
function getFilenameParams(contentDisposition: string): { filenamestar?: string, filename?: string } {
// Split using ; (if not quoted) and skip the first element since it's `disposition-type`
const [, ...dispositionParams] = contentDisposition.split(/(?!\B"[^"]*);\s(?![^"]*"\B)/);
return {
filenamestar: getParamValue('filename\\*', dispositionParams),
filename: getParamValue('filename', dispositionParams),
};
}
function getParamValue(paramName: string, params: string[]): string | undefined {
const regex = new RegExp('^\\s*' + paramName + '=(?<paramValue>.+)\\s*$', 'i');
return params.find(p => p.match(regex)?.groups?.['paramValue']);
}
this.http.get(/*...*/).pipe(
map(response => {
const contentDisposition = response.headers.get('content-disposition');
if (!contentDisposition) {
throw new Error('content-disposition header not found');
}
const filename = parseContentDispositionFilename(contentDisposition);
/*...*/
Upvotes: 0
Reputation: 30
There are a lot of other good answers here - here's what I ended up with that worked best for me against an ASP.NET Core 3.1 server, using a lot of these as a guide.
function getFilename() {
const header = response.headers.get("Content-Disposition");
if (!header) {
return null;
}
let matches = /filename=\"?([^;"]+)\"?;?/g.exec(header);
return matches && matches.length > 1 ? matches[1] : null;
}
Upvotes: 0
Reputation: 632
// SERVICE
downloadFile(params: any): Observable<HttpResponse<any>> {
const url = `https://yoururl....etc`;
return this.http.post<HttpResponse<any>>(
url,
params,
{
responseType: 'blob' as 'json',
observe: 'response' as 'body'
})
.pipe(
catchError(err => throwError(err))
);
}
// COMPONENT
import * as FileSaver from 'file-saver';
... some code
download(param: any) {
this.service.downloadFile(param).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;
FileSaver.saveAs(fileContent, fileName);
},
error: (error) => {
console.log({error});
}
});
}
Enjoy
Upvotes: 5
Reputation: 485
success(function(data, status, headers, response,xhr) {
console.log(headers('Content-Disposition'));
}
Upvotes: 1
Reputation: 1089
Web API: I found that adding the following line of code into the ExecuteAsync(...) method of my IHttpActionResult implementation worked ('response' is the HttpResponseMessage to be returned):
response.Content.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
Angular: I was then able to resolve the filename in angular as follows ('response' is the resolved promise from $http.get):
var contentDisposition = response.headers('Content-Disposition');
var filename = contentDisposition.split(';')[1].split('filename')[1].split('=')[1].trim();
Upvotes: 30
Reputation: 1070
Similar to some of the above answers but using a basic RegEx is how I solved it instead:
let fileName = parseFilenameFromContentDisposition(response.headers('Content-Disposition'));
function parseFilenameFromContentDisposition(contentDisposition) {
if (!contentDisposition) return null;
let matches = /filename="(.*?)"/g.exec(contentDisposition);
return matches && matches.length > 1 ? matches[1] : null;
}
Upvotes: 12
Reputation: 1715
If response.headers('Content-Disposition')
returns null, use response.headers.**get**('Content-Disposition');
.
The rest of @andrew's snippet now works great.
Upvotes: 4
Reputation: 548
If you use CORS, you need to add the "Access-Control-Expose-Headers" to the response headers at server side. For example: Access-Control-Expose-Headers: x-filename, x-something-else
Upvotes: 16
Reputation: 8038
It may be worth mentioning that in order to get the file name from the HTTP headers, extracting the Content-Disposition
header is not enough.
You still need to obtain the filename
property from this header value.
Example of header value returned: attachment; filename="myFileName.pdf"
.
The function below will extract filename="myFileName.pdf"
, then extract "myFileName.pdf"
and finally remove the extra quotes around to get myFileName.pdf
.
You can use the snippet below:
function getFileNameFromHttpResponse(httpResponse) {
var contentDispositionHeader = httpResponse.headers('Content-Disposition');
var result = contentDispositionHeader.split(';')[1].trim().split('=')[1];
return result.replace(/"/g, '');
}
Upvotes: 52
Reputation: 97
Maybe you already find solution, but I will post this answer if someone else has this problem.
Add these parameters in the success callback function from the $http request:
$http.get(myUrl).success(function (data, status, headers, config) {
// extract filename from headers('Content-Disposition')
});
Upvotes: 4
Reputation: 28339
Use response.headers
to get http response headers:
$http.get(myUrl).then(function (response) {
// extract filename from response.headers('Content-Disposition')
}
Upvotes: 6