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