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

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

    // SERVICE

    downloadFile(params: any): Observable<HttpResponse<any>> {
    
        const url = `https://yoururl....etc`;
    
    
        return this.http.post<HttpResponse<any>>(
          url,
          params,
          {
            responseType: 'blob' as 'json',
            observe: 'response' as 'body'
          })
          .pipe(
            catchError(err => throwError(err))
          );
      }
    

    // COMPONENT

    import * as FileSaver from 'file-saver';
    
    ... some code
    
      download(param: any) {
        this.service.downloadFile(param).pipe(
        ).subscribe({
          next: (response: any) => {
    
            let fileName = 'file';
            const contentDisposition = response.headers.get('Content-Disposition');
            if (contentDisposition) {
              const fileNameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
              const matches = fileNameRegex.exec(contentDisposition);
              if (matches != null && matches[1]) {
                fileName = matches[1].replace(/['"]/g, '');
              }
            }
    
            const fileContent = response.body;
    
            FileSaver.saveAs(fileContent, fileName);
    
          },
          error: (error) => {
    
            console.log({error});
    
          }
        });
      }
    

    Enjoy

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

    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;
    }
    
    0 讨论(0)
  • 2021-02-01 16:24

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

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

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

    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')
        });
    
    0 讨论(0)
  • 2021-02-01 16:29

    Use response.headers to get http response headers:

    $http.get(myUrl).then(function (response) {
        // extract filename from response.headers('Content-Disposition')
    } 
    
    0 讨论(0)
  • 2021-02-01 16:29
    success(function(data, status, headers, response,xhr) {
        console.log(headers('Content-Disposition'));
    }
    
    0 讨论(0)
提交回复
热议问题