How to get the name of a file downloaded with Angular $http?

て烟熏妆下的殇ゞ 提交于 2019-12-03 02:19:57

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

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

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();

Use response.headers to get http response headers:

$http.get(myUrl).then(function (response) {
    // extract filename from response.headers('Content-Disposition')
} 

Similar to some of the above answers but using a basic RegEx is how I solved it instead:

let fileName = parseFilenameFromContentDisposition(response.headers('Content-Disposition'));

function parseFilenameFromContentDisposition(contentDisposition) {
    if (!contentDisposition) return null;
    let matches = /filename="(.*?)"/g.exec(contentDisposition);

    return matches && matches.length > 1 ? matches[1] : null;
}

Maybe you already find solution, but I will post this answer if someone else has this problem.

Add these parameters in the success callback function from the $http request:

    $http.get(myUrl).success(function (data, status, headers, config) {
        // extract filename from headers('Content-Disposition')
    });
andreisrob

If response.headers('Content-Disposition') returns null, use response.headers.**get**('Content-Disposition');.

The rest of @andrew's snippet now works great.

success(function(data, status, headers, response,xhr) {
    console.log(headers('Content-Disposition'));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!