AEM-User generated collections-dowload
Hello, AEM community.
We have a requirement to download the dam user-generated collection. As part of it, we read all collection items into an array and iterate through them using the code below. It sometimes works, but for huge files or files longer than 4-5 files, there is a problem with the last or first file.
if (!!collectionPath) {
const collectionItemsArr = collectionPath.split(';'); // Split paths by ';'
console.log("collectionItemsArr::",collectionItemsArr);
if (collectionItemsArr.length > 0) {
const filename = collectionTitle;
let url = collectionItemsArr[0] + ".assetdownload.zip/" + encodeURIComponent(filename);
const promises = [];
if (collectionItemsArr.length > 1) {
for (let i = 0; i < collectionItemsArr.length; i++) {
collectionItemsArr[i] = collectionItemsArr[i];
}
url = addParameter(url, "path", collectionItemsArr);
}
url = addParameter(url, "_charset_", "utf-8");
url = addParameter(url, "licenseCheck", "true");
url = addParameter(url, "flatStructure", "true");
window.localStorage.removeItem("nonLicensedAssetPaths");
promises.push(downloadFile(url));
try {
// Wait for all downloads to complete
await Promise.all(promises);
} catch (error) {
console.error('Error downloading files:', error);
}
}
const downloadFile = (url) => {
return new Promise((resolve, reject) => {
const downloadWindow = window.open(url, "_blank");
if (downloadWindow) {
// Resolve the promise when the download is complete
downloadWindow.onload = () => {
resolve();
};
} else {
reject(new Error("Failed to open download window"));
}
});
};
function addParameter(url, paramName, paramValue) {
if (paramValue && paramValue instanceof Array) {
for (let i = 0; i < paramValue.length; i++) {
url = addParameter(url, paramName, paramValue[i]);
}
return url;
}
const separator = url.indexOf("?") == -1 ? "?" : "&";
const hashIdx = url.indexOf("#");
if (hashIdx < 0) {
return url + separator + encodeURIComponent(paramName) + "=" + encodeURIComponent(paramValue);
} else {
const hash = url.substring(hashIdx);
url = url.substring(0, hashIdx);
return url + separator + encodeURIComponent(paramName) + "=" + encodeURIComponent(paramValue) + hash;
}
}
Please help me.
