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

前端 未结 10 763
一生所求
一生所求 2021-02-01 15:36

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, wh

10条回答
  •  南方客
    南方客 (楼主)
    2021-02-01 16:39

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

提交回复
热议问题