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

前端 未结 10 758
一生所求
一生所求 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:34

    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

    0 讨论(0)
  • 2021-02-01 16:37

    There are a lot of other good answers here - here's what I ended up with that worked best for me against an ASP.NET Core 3.1 server, using a lot of these as a guide.

    function getFilename() {
        const header = response.headers.get("Content-Disposition");
        if (!header) {
            return null;
        }
    
        let matches = /filename=\"?([^;"]+)\"?;?/g.exec(header);
    
        return matches && matches.length > 1 ? matches[1] : null;
    }
    
    0 讨论(0)
  • 2021-02-01 16:38

    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();
    
    0 讨论(0)
  • 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, '');
      }
    
    0 讨论(0)
提交回复
热议问题