Skip to content

Instantly share code, notes, and snippets.

@oshikryu
Last active September 27, 2017 18:12
Show Gist options
  • Save oshikryu/f8b4a26cb006665797d49cf01016276f to your computer and use it in GitHub Desktop.
Save oshikryu/f8b4a26cb006665797d49cf01016276f to your computer and use it in GitHub Desktop.
getting attachments in two ways
/*
Which implementation would you prefer for downloading bulk attachments? (e.g. click download and
expect 3+ images)
1) One implementation requires the addition of 3 new libraries to make a zip file (which a user will just unzip
anyway)
However, it looks pretty straightforward
*/
import JSZip from 'jszip';
import JSZipUtils from 'jszip-utils';
import { saveAs } from 'file-saver';
const zip = new JSZip();
const zipFilename = "attachments.zip";
files.forEach((file, idx) => {
// here, the image is fetched from the server, only to be zipped
JSZipUtils.getBinaryContent(href, function (err, data) {
if (err) {
throw err;
}
// add file to zip
zip.file(title, data, {binary:true});
if (idx === files.length - 1) {
zip.generateAsync({type:'blob'}).then(function(content) {
// force download of created zip file
saveAs(content, zipFilename);
});
}
});
//OR
/*
2) download all the files individually, unzipped
*/
files.forEach(file => {
downloadFile(href, filename);
})
//where download file looks like:
export function downloadFile(href, filename) {
let link = document.createElement("a");
link.setAttribute("href", href);
link.setAttribute("download", filename);
document.body.appendChild(link);
link.click(); // This will download the data file
document.body.removeChild(link);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment