How to Download a File with Angular2 or Greater

How do I download a file with Angular2 or greater

The problem is that the observable runs in another context, so when you try to create the URL var, you have an empty object and not the blob you want.

One of the many ways that exist to solve this is as follows:

this._reportService.getReport().subscribe(data => this.downloadFile(data)),//console.log(data),
error => console.log('Error downloading the file.'),
() => console.info('OK');

When the request is ready it will call the function "downloadFile" that is defined as follows:

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

the blob has been created perfectly and so the URL var, if doesn't open the new window please check that you have already imported 'rxjs/Rx' ;

import 'rxjs/Rx' ;

I hope this can help you.

how to download file in angular 2 typescript

you can use FileSave package exist in npm:

npm install --save file-saver
..
import { saveAs } from 'file-saver/FileSaver';

then in your method in subscribe after get result use like bellow

saveAs(result, filename);

Angular: How to download a file from HttpClient?

Try something like this:

type: application/ms-excel

/**
* used to get file from server
*/

this.http.get(`${environment.apiUrl}`,{
responseType: 'arraybuffer',headers:headers}
).subscribe(response => this.downLoadFile(response, "application/ms-excel"));

/**
* Method is use to download file.
* @param data - Array Buffer data
* @param type - type of the document.
*/
downLoadFile(data: any, type: string) {
let blob = new Blob([data], { type: type});
let url = window.URL.createObjectURL(blob);
let pwa = window.open(url);
if (!pwa || pwa.closed || typeof pwa.closed == 'undefined') {
alert( 'Please disable your Pop-up blocker and try again.');
}
}

Angular and Nodejs basic file download

There you go..

Node.js Server:

const express = require("express");
const router = express.Router();

router.post("/experiment/resultML/downloadReport",downloadReport);

const downloadReport = function(req, res) {
res.sendFile(req.body.filename);
};

Component Angular:

  import { saveAs } from "file-saver"
download() {
let filename = "/Path/to/your/report.pdf";
this.api.downloadReport(filename).subscribe(
data => {
saveAs(data, filename);
},
err => {
alert("Problem while downloading the file.");
console.error(err);
}
);
}

Service Angular:

  public downloadReport(file): Observable<any> {
// Create url
let url = `${baseUrl}${"/experiment/resultML/downloadReport"}`;
var body = { filename: file };

return this.http.post(url, body, {
responseType: "blob",
headers: new HttpHeaders().append("Content-Type", "application/json")
});
}

How do I download a file with Angular2 or greater

The problem is that the observable runs in another context, so when you try to create the URL var, you have an empty object and not the blob you want.

One of the many ways that exist to solve this is as follows:

this._reportService.getReport().subscribe(data => this.downloadFile(data)),//console.log(data),
error => console.log('Error downloading the file.'),
() => console.info('OK');

When the request is ready it will call the function "downloadFile" that is defined as follows:

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

the blob has been created perfectly and so the URL var, if doesn't open the new window please check that you have already imported 'rxjs/Rx' ;

import 'rxjs/Rx' ;

I hope this can help you.

Download a file in Angular 2

I got it to work, and this is my answer below:

downloadDocument(docId){
const headers = new Headers({responseType:ResponseContentType.Blob});
headers.append('authorization','Bearer '+token);
this.http.get(url,{headers:headers,responseType:ResponseContentType.Blob}).subscribe(
(response) => {
FileSaver.saveAs(response.blob(), "Document-" + docId+ ".pdf");
}
);
}

Import FilSaver

import * as FileSaver from 'file-saver';


Related Topics



Leave a reply



Submit