Skip to content

Instantly share code, notes, and snippets.

@theinventor
Created May 7, 2024 02:16
Show Gist options
  • Save theinventor/8ceed295344077c04523675d18fb55dc to your computer and use it in GitHub Desktop.
Save theinventor/8ceed295344077c04523675d18fb55dc to your computer and use it in GitHub Desktop.
A simple function in a stimulus controller in rails. It will post IDs of your objects to an endpoint to fetch their public URLs, then zip up all those files from the public URLs and give them a download.zip file.
async download(event) {
event.preventDefault();
console.log("Download function initiated");
const spinner = document.querySelector('.downloadLoading'); // Show the spinner
spinner.classList.remove('hidden');
const contentIds = this.selectedIds;
const csrfToken = document.querySelector("[name='csrf-token']").content;
const headers = new Headers({
'Content-Type': 'application/json',
'X-CSRF-Token': csrfToken
});
const fetchOptions = {
method: 'POST',
headers: headers,
body: JSON.stringify({ contentIds: contentIds }),
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin'
};
try {
const appResponse = await fetch('/contents/bulk_download', fetchOptions);
if (!appResponse.ok) throw new Error('Network response was not ok when fetching URLs.');
const { urls } = await appResponse.json();
if (urls && urls.length > 0) {
const zip = new JSZip();
await Promise.all(urls.map(url =>
fetch(url)
.then(response => {
if (!response.ok) throw new Error(`Failed to fetch ${url}`);
return response.blob();
})
.then(blob => {
// Extract filename without query parameters
const filename = new URL(url).pathname.split('/').pop();
zip.file(filename, blob);
})
));
zip.generateAsync({ type: "blob" }).then(function(content) {
const a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
a.href = URL.createObjectURL(content);
a.download = `download_${new Date().getTime()}.zip`;
a.click();
a.remove();
console.log('Download completed successfully');
});
} else {
throw new Error('No URLs were returned from the application.');
}
} catch (error) {
console.error("Error during download:", error);
alert('Failed to download the files: ' + error.message);
} finally {
spinner.classList.add('hidden'); // Hide the spinner
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment