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, wh
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
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;
}
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();
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, '');
}