Skip to content

Instantly share code, notes, and snippets.

@kksrini89
Last active August 17, 2021 10:21
Show Gist options
  • Select an option

  • Save kksrini89/de02eaf334018562f99bfde1a34e0621 to your computer and use it in GitHub Desktop.

Select an option

Save kksrini89/de02eaf334018562f99bfde1a34e0621 to your computer and use it in GitHub Desktop.
Downloading file in Angular - from Node.js
downloadFile(token: string, url: string) {
try {
let headers = new HttpHeaders()
.set(
'Authorization',
`Bearer ${token}`
)
.set('Accept', 'text/csv');
this.http
.get(`${url}`, {
headers: headers,
responseType: 'blob'
})
.subscribe(
data => {
// Without File name
/*console.log('success', data);
const blob = new Blob([data], { type: 'text/csv' });
const url = window.URL.createObjectURL(blob);
window.open(url);*/
// With FileName
const blob: Blob = new Blob([data], { type: 'text/csv' });
const fileName = 'budget.csv';
const objectUrl: string = URL.createObjectURL(blob);
const a: HTMLAnchorElement = document.createElement('a') as HTMLAnchorElement;
a.href = objectUrl;
a.download = fileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(objectUrl);
},
error => console.log('oops', error)
);
} catch (error) {
console.log(error);
throw error;
}
}
Reference links
-----------------
https://stackoverflow.com/questions/50039015/how-to-download-a-pdf-file-from-an-url-in-angular-5
https://stackoverflow.com/questions/35138424/how-do-i-download-a-file-with-angular2
https://stackoverflow.com/questions/43235129/typescript-blob-filename-without-link
https://github.com/mholt/PapaParse/issues/175#issuecomment-75597039
router.get('/export_to_csv/:id', bearer.Handler, async (req, res, next) => {
try {
const { id } = req.params;
let action = new exportCSV(id);
ActionManager.execute(action)
.then(result => {
res.setHeader('Content-Disposition', 'attachment; filename=filename.csv');
res.set('Content-Type', 'text/csv');
res.status(200);
res.send(result);
})
.catch(error => {
res.status(error.status || 400).json({ error: error.message });
});
} catch (error) {
res.status(error.status || 400).json({ error: error.message });
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment