简体   繁体   中英

Angular: How to get the file name of the uploaded file

Following is my Response header for POSTMAN request:

Content-Disposition: attachment; filename="file_name.docx.docx"

where file_name is the actual file name

Now, while downloading the file in Angular, I want this exact name. But instead of that, every time I download the file it picks up some random name

Following is my angular code:

this.http.get("url", {responseType: 'blob'}).subscribe((res) => {
  const blob = new Blob([res], {type: 'application/msword'});
  const url = window.URL.createObjectURL(blob);
  window.open(url);
})

Is there any I can get the exact name of the file which we want to download, ie the same name which I am getting in Postman request header

Could you try this below method using observe and see if it fixes the issue?

ts

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  name = 'Angular';
  constructor(private http: HttpClient) {}

  ngOnInit() {
    this.http
      .get(
        'https://www.mtsac.edu/webdesign/accessible-docs/word/example03.docx',
        {
          responseType: 'blob' as 'json',
          observe: 'response' as 'body',
        }
      )
      .subscribe(async (res: any) => {
        console.log(res);
        const filename = res.headers.get('filename') || 'test.docx';
        const blob = res.body;
        const blobFinal = new Blob([blob as Blob], {
          type: 'application/msword',
        });
        const url = window.URL.createObjectURL(blobFinal);
        console.log(url);
        var fileLink = document.createElement('a');
        fileLink.href = url;
        fileLink.download = filename;
        fileLink.click();
      });
  }
}

forked stackblitz

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM