Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I download file using Angular 5?

When I paste my_example_link in a browser the file is automatically downloaded in a proper way. However, when I use source code shown below download doesn't work. I would like to download file after clicking download button. Any ideas what is wrong? I don't get any errors.

user.service.ts:

DownloadFiles() {

    return this.http.get('my_example_link', {responseType: 'text'});

}

uploader.service.ts:

DownloadFile(){

      this.userService.DownloadFiles()
          .subscribe(
              (data) => this.downloadFile2(data)), // console.log(data),
              (error) => console.log("Error downloading the file."),
              () => console.info("OK");
}

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

something.component.html:

<li class="nav-item" *ngIf="isCloud()">
    <a  (click)="this.UploaderService.DownloadFile()" download="file23.txt" style='cursor: pointer;' class="nav-link" target="_blank">
        <i class="nc-icon nc-basket"></i> Download
    </a>
</li>
like image 614
thedbogh Avatar asked Aug 21 '18 15:08

thedbogh


1 Answers

Use arraybuffer

this.httpClient.get(url, {responseType: 'arraybuffer',headers:headers});

To save File:

 npm install file-saver --save

 import { saveAs } from 'file-saver/FileSaver';

component:

downLoadFile(data: any, type: string) {
        var blob = new Blob([data], { type: type.toString() });
        var url = window.URL.createObjectURL(blob);
        saveAs(blob,"file_name.txt");
        window.open(url);

    }
like image 161
Akj Avatar answered Oct 19 '22 03:10

Akj