KnowledgeSeeker001
KnowledgeSeeker001

Reputation: 638

How can i download a file with a specific name in angular typescript?

Hi Following is a small snippet of code in my angular component.

this.messageHistoryService.getMessageHistoriesCSV1(msgHistoryRequest).subscribe(
  (data) => {
    console.log(data.messageHistoryBytes);
   let file = new Blob( [data.messageHistoryBytes] , { type: 'plain/text' });   
   let fileURL = URL.createObjectURL(file);
    window.open(fileURL);
  }
);

the above code works and downloads file in the browser . How ever i would like to give a specific name to the downloaded file for example download.csv . . how can i achieve that.

Upvotes: 1

Views: 1712

Answers (3)

KnowledgeSeeker001
KnowledgeSeeker001

Reputation: 638

this.messageHistoryService.getMessageHistoriesCSV1(msgHistoryRequest).subscribe(
  (data) => {

    console.log(data.messageHistoryBytes);


   let file = new Blob( [data.messageHistoryBytes] , { type: 'plain/text' });   
   let fileURL = URL.createObjectURL(file);

   // window.open(fileURL);

  var linkToFile = document.createElement('a');
  linkToFile.download = "message-history.csv";
  linkToFile.href = fileURL;
  linkToFile.click();

    this.executingElasticSearchQuery = false;

  }

);

i rewrite the code like this and it works

Upvotes: 0

Miguel Pinto
Miguel Pinto

Reputation: 563

Try replace your

window.open(fileURL);

to:

 window.navigator.msSaveOrOpenBlob(file , "filename");

Upvotes: 1

Flo
Flo

Reputation: 986

The tip is to create a 'temporary' <a> tag and simulate a click on it.

Try this:

var linkToFile = document.createElement('a');
linkToFile.download = filename;
linkToFile.href = fileURL;
linkToFile.click();

Upvotes: 1

Related Questions