Unlinked Typescript blob file name

Is there a way to set the file name for a blob in typescript? I have found a solution for IE, but it seems impossible for Chrome. I need something similar to this solution, but in typescript.

downloadFile(data: any) {
    var blob = new Blob([data], {type: 'text/csv'});
    let fileName = 'my-test.csv';

    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        //save file for IE
        window.navigator.msSaveOrOpenBlob(blob, fileName);
    } else {
        //save for other browsers: Chrome, Firefox

        var objectUrl = URL.createObjectURL(blob);
        window.open(objectUrl);
    }
}

This function is called from an HTML UI/Angular 2:

<button type="button" class="btn btn-success"
(click)="downloadFile('test')">Download <br /> Download </button>

Answer №1

If you're using chrome or firefox, there's a workaround you can do to download a file by creating an <a> element and triggering the click event:

downloadFile(data: any): void {
    const blog: Blob = new Blob([data], {type: 'text/csv'});
    const filename: string = 'my-file.csv';
    const url: string = URL.createObjectURL(blob);
    const link: HTMLAnchorElement = document.createElement('a') as HTMLAnchorElement;

    link.href = url;
    link.download = filename;
    document.body.appendChild(link);
    link.click();

    document.body.removeChild(link);
    URL.revokeObjectURL(url);
}

Answer №2

Below is a functioning download function that is compatible with IE, Chrome, and Firefox:

  saveAsCsv(data, fileName) {
    const csvFileName = fileName +  '.csv';
    const blob = new Blob([data], {type: 'text/csv'});
    if (window.navigator && window.navigator.msSaveOrOpenBlob) { // For Internet Explorer
      window.navigator.msSaveOrOpenBlob(blob, csvFileName);
      window.navigator.msSaveOrOpenBlob(blob, csvFileName);
    } else { // For Chrome and Firefox
      const link = document.createElement('a');
      const url = window.URL.createObjectURL(blob);
      link.href = url;
      link.download = csvFileName;
      link.click();
      window.URL.revokeObjectURL(url);
      link.remove();
    }
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Finding the row index in an Angular material table

How can I retrieve the row index in an Angular material table? <td mat-cell *matCellDef="let row"> <mat-checkbox (click)="$event.stopPropagation()&quo ...

How can I store the data retrieved from an API and then forward it to a URL using Angular?

Is there a way to save and pass the data received from an API to a URL in Angular? SERVICE.ts readonly apiUrl = 'http://localhost:49940/'; constructor(private http: HttpClient) { } getUserName(): Observable<any> { return this.http.ge ...

multiple event listeners combined into a single function

I'm looking to streamline my button handling in JavaScript by creating just one function that can handle all the buttons on my page. Each button will trigger a different action, so I need a way to differentiate between them. I thought of using one eve ...

`Is it possible to integrate npm libraries with typescript and ES6?`

I am looking to focus on using ES6 as the output for a node server-side app that I plan to run on the cutting-edge iojs distribution, which hopefully has support for the latest ES6 syntax. However, I'm unsure about how to integrate standard NPM libra ...

Performing an insertion in TypeORM with a foreign key connection

In my database schema, I have set up a relationship where each Chatroom can have multiple Messages linked to it. However, when I try to insert a Message (or a batch of Messages), the foreign key for ChatRoom is not being assigned properly and remains null. ...

Tips on creating type definitions for CSS modules in Parcel?

As someone who is brand new to Parcel, I have a question that may seem naive. In my project, I am using typescript, react, less, and parcel. I am encountering an error with typescript stating 'Cannot find module 'xxx' or its corresponding t ...

What is the best way to form a new type that encompasses all shared properties found within a union of types?

Is there a method to safely map over the union of arrays without hard-coding specific types? When attempting to calculate newArr1, an error is encountered: Property 'field2' does not exist on type 'Common<A, B>'. How can this err ...

Trouble installing Angular: ENOENT Error causing issues

Currently in the process of setting up angular. I have been diligently following the provided installation instructions, but when executing npm install -g @angular/cli, I encounter the error shown in the screenshot below. Here are the versions of node and ...

Which ngTagsInput version is recommended for Angular instead of AngularJs?

After discovering the ngTagsInput framework on this site, I found it to be a very comprehensive library. However, for Angular 8 users like myself, I came across the ngx-chips framework on this page. While ngx-chips seems to work, I noticed that it lacks s ...

Assigning a value and specifying the selected attribute for an options tag

Trying to understand the challenge of setting both a value and a selected attribute on an options tag. Each one works independently, but not together. For example: <select> <option *ngFor="let item of items" selected [ngValue]="item"> ...

How can we detect if the pressing of an "Enter" key was triggered by an Angular Material autocomplete feature?

Currently, I have incorporated an Angular Material Autocomplete feature into my search bar. When a user types in their query and presses the Enter key, the search is executed as expected. Nevertheless, if the user decides to select one of the autocomplete ...

New Chrome update restricts insecure cookies from functioning in Angular

We have been utilizing the ngx-cookie-service to establish session cookies for our logged-in users. Everything was functioning properly until yesterday when the latest Chrome update began blocking unsecure cookies and displaying a warning message in the co ...

Error loading ngs-boostrap in angular2: issues encountered during initialization

Attempting to implement a dropdown menu using ng2-bootstrap component, but encountering an error upon access: Error message received: Failed to load resource: the server responded with a status of 404 (Not Found) Steps taken so far: 1) Installed ng2-boo ...

Verifying the presence of an object in an array based on its value using TypeScript

Having the following dataset: roles = [ {roleId: "69801", role: "ADMIN"} {roleId: "69806", role: "SUPER_ADMIN"} {roleId: "69805", role: "RB"} {roleId: "69804", role: "PILOTE"} {roleId: "69808", role: "VENDEUR"} {roleId: "69807", role: "SUPER_RB"} ] The o ...

"Using the power of jQuery to enhance the loading of Google Chrome

When attempting to load jQuery in the manifest's content_scripts, I encounter an issue where a dropdown stops working on a page that already has jQuery loaded. Despite checking the console log for errors, I am unable to pinpoint the issue. Removing jQ ...

Navigating through async functions in an Express.js router

Encountered a lint error indicating that Promises cannot be returned in places where a void is expected. Both functions [validateJWT, getUser] are async functions. Any suggestions on how to resolve this issue without compromising the linter guidelines by u ...

What is the best method to display and conceal a table row in Angular 6?

In the midst of developing a table with multiple rows, I am seeking a way to invisibilize a particular row and then reveal it again using a reset button. Any tips on how to accomplish this task?emphasis added ...

html td elements are breaking due to the application of ngFor

<table> <tr> <th>Date</th> <th>Products</th> </tr> <tr *ngFor="let x of orderdetails"> <td>{{x.orderdate}}</td> <td *ngFor="let y of x.orderproducts"> <span class="break">{{y}}</s ...

Using Angular-Meteor to make an HTTP request

I'm attempting to utilize the HTTP.call method with angular-meteor. Within my API backend folder, I am trying the following within a method: this.unblock(); try { const result = HTTP.call('GET', 'https://api.foursquare.com/v2/users/ ...

Loading tabs dynamically in Angular 2 based on header click event

I successfully created a custom tab component using Angular 2, and it is functioning well with the following usage: <us-tab-verticle> <vtab-content [tabTitle]="'Basic Information'"><basic-info> </basic-info></vtab- ...