Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve HttpResponseMessage FileName in JavaScript

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 a HttpResponseMessage. Note that I specify the filename on 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 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?

like image 958
dhrm Avatar asked Mar 16 '15 07:03

dhrm


1 Answers

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.

like image 107
Nikos Paraskevopoulos Avatar answered Sep 22 '22 17:09

Nikos Paraskevopoulos