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

前端 未结 10 950
一生所求
一生所求 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> {
    
        const url = `https://yoururl....etc`;
    
    
        return this.http.post>(
          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

提交回复
热议问题