How to retrieve HttpResponseMessage FileName in JavaScript
The promise returned by methods of $http
are passed as argument an object with the following properties (ref):
- data – {string|Object} – The response body transformed with the transform functions.
- status – {number} – HTTP status code of the response.
- headers – {function([headerName])} – Header getter function.
- config – {Object} – The configuration object that was used to generate the request.
- statusText – {string} – HTTP status text of the response.
So results.headers('Content-Disposition')
will gives you the value of the Content-Disposition
header. You will have to do some trivial parsing to get to the actual filename.
Related videos on Youtube
dhrm
Updated on September 15, 2022Comments
-
dhrm over 1 year
I've this WebAPI method, that takes a custom object
MyType
as input and generate a PDF based on that. The PDF-file is returned as aHttpResponseMessage
. Note that I specify the filename onresponse.Content.Headers.ContentDisposition.FileName
:ASP.NET WebAPI
[Route("")] public HttpResponseMessage Get([FromUri]MyType input) { var pdfContent = PdfGenerator.Generate(input); var response = new HttpResponseMessage(HttpStatusCode.OK); response.Content = pdfContent; response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment"); response.Content.Headers.ContentDisposition.FileName = "MyCustomFileName.pdf" return response; }
In AngularJS I fetch the file using FileSaver.js like this:
$http.get("api/pdf/", { params: { "type": myObject }, responseType: 'arraybuffer' }).then(function (results) { var data = results.data; var file = new Blob([data], { type: 'application/pdf' }); saveAs(file, 'filename.pdf'); }, function (results) { console.log(results); });
It works as excepted, but I'm defining the filename both on WebAPI and in the JavaScript. Is there a way, that I can retrieve the FileName defined in WebAPI in the
results
variable in JavaScript? -
Jitender Kumar over 7 yearsThis above solution is not working in Chrome as it just return the headers
Cache-Control
andContent-Type
. Here is my post for more detail stackoverflow.com/questions/39825590/… -
Nikos Paraskevopoulos almost 7 yearsThe previous comment is wrong because, as it is obvious from the answer of the linked question, the problem in the question is not Chrome, but the fact that the request is CORS and it needs explicit permission to access headers.