'Download multiple files using S3 pre-signed url in my Angular Application
I am making REST API call to get an array of pre-signed URLs from S3. These URL are files that could be XML, CSV, JSON etc.
How do I loop download files from these URLs without opening a new tab? I do not want to use AWS SDK for NodeJS to avoid tight coupling with my front-end. Application currently has Angular 7, NodeJS and ExpressJS.
getFile(url, params){
this.awsservice.getFile(url, params).subscribe(
(response) => {
const res = JSON.parse(JSON.stringify(response));
var apiList = [];
for (var key in res) {
if(key == 'api'){
apiList = res[key];
}
}
apiList.forEach(function (url) {
// Logic to download file
document.location.assign(url) //Only seems to download the last file in the array
console.log("Download started: "+url);
});
},
(error) => {
this.tempErrorFlag = true;
const errorMsg = error;
console.log(`ERROR ::: reInitiate API ::: ${errorMsg.message}`);
});
}
I tried adding document.location.assign(url) but it only seems to download the last url in the array. Even adding delay didn't help.
Appreciate your help.
Solution 1:[1]
I was able to download the files but not in the same tab. First I fetch presigned URLs from my angular service, which I feed into an array. Then basically with each of the presigned urls, I create a temporary anchor tag to and assign href the presigned url value. The snackbarService is for showing a popup when the download begins. The entire code looks like below:
downloadItem() {
let urls = [];
for(let item of this.selectedRowsData) {
//calling the service to fetch the presigned url
this.dataService.getPresignedToDownloadAll(
item.value,
item.id).subscribe((res) => {
urls.push(res);
this.download(urls);
});
}
}
download(urls: any) {
var self = this;
var url = urls.pop();
setTimeout(function(){
self.snackBarService.loadComponent({
isSuccess: true,
message: MESSAGES.downloadInProgress,
});
var a = document.createElement('a');
a.setAttribute('href', url);
document.body.appendChild(a);
a.setAttribute('download', '');
a.setAttribute('target', '_blank');
a.click();
// a.remove();
}, 1000)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Manit |
