skip to Main Content

Window

mac

And solution should work on Windows and mac, and also we can give default file name, and type also

3

Answers


  1. Chosen as BEST ANSWER

    downloadFile(data: any, filename: string = 'default.csv') {
      const blob = new Blob([data], { type: 'csv' });
      const url = URL.createObjectURL(blob);
      const anchorElement = document.createElement('a');
      anchorElement.href = url;
      anchorElement.setAttribute('download', filename);
      anchorElement.style.display = 'none';
      document.body.appendChild(anchorElement);
      anchorElement.click();
      document.body.removeChild(anchorElement);
      URL.revokeObjectURL(url);
    }

    to get pop up, you have to change your browsers settings (Ask where to save each file before downloading) enter image description here


  2. Try the following example:

    downloadFile(data: Response) {
       const blob = new Blob([data], { type: 'text/csv' });
       const url= window.URL.createObjectURL(blob);
       window.open(url);
    }
    

    Another way is:

    1 – Install dependencies for show save/open file pop-up

    npm install file-saver --save
    npm install -D @types/file-saver
    

    2- Create a service with this function to receive the data

    downloadFile(id): Observable<Blob> {
    let options = new RequestOptions({responseType: 
       ResponseContentType.Blob });
       return this.http.get(this._baseUrl + '/' + id, options)
          .map(res => res.blob())
          .catch(this.handleError)
    }
    

    3- In the component parse the blob with ‘file-saver’

    import {saveAs as importedSaveAs} from "file-saver";
    
    this.myService.downloadFile(this.id).subscribe(blob => {
        importedSaveAs(blob, this.fileName);
    });
    
    Login or Signup to reply.
  3. You can make use of showSaveFilePicker, but its browser support is very limited. It may work with Chrome/Edge in Windows & Mac, but won’t work in mobile.

    e.g. : The following code will download a text file with ‘Save As’ dialog box.

        const saveOptions = {
            excludeAcceptAllOption: false, 
            suggestedName: 'SuggestName.txt',
            types: [{
                accept: { "text/plain": [".txt"] },
                description: 'A plain text'
            }]
        };
        const newHandle = await window.showSaveFilePicker(saveOptions);
        const writableStream = await newHandle.createWritable();
        let blob = new Blob(['Hello, world!'], {type: 'text/plain'});
        await writableStream.write(blob);
        await writableStream.close();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search