How to get HttpResponseMessage filename in JavaScript

I have this WebAPI method that takes a custom MyType object as input and generates a PDF based on this. The PDF file is returned as an HttpResponseMessage . Note that I point the file name to response.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 retrieve a file using FileSaver.js as follows:

 $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 excluded, but I define the file name in both WebAPI and JavaScript. Is there a way so that I can get the file name defined in WebAPI in the results variable in JavaScript?

+8
javascript angularjs asp.net-web-api
source share
1 answer

The promise returned by the $http methods is passed as an argument to the object with the following properties ( ref ):

  • data - {string | Object} is the response body transformed using the conversion functions.
  • status - {number} - The HTTP status code for the response.
  • headers - {function ([headerName])} - the function of the header receiver.
  • config - {Object} - the configuration object that was used to generate the request.
  • statusText - {string} - response text of the HTTP response.

So results.headers('Content-Disposition') will give you the value of the Content-Disposition header. You will need to do some trivial showdowns to get to the actual file name.

+6
source

All Articles