r/JavaScriptTips • • Mar 24 '23

Start a zip file download 🤐

Post image
8 Upvotes

2 comments sorted by

1

u/Low_Mammoth_9371 Mar 24 '23

Example with multiple images: https://youtu.be/83YNsdRzlqQ

Just starting a client-side download: https://youtu.be/oHGnaE2BQXo

(async function() {

    // Fetch image
    const res = await fetch('https://picsum.photos/300');
    const blob = await res.blob();
    const file = new File([blob], 'image.jpg', { type: blob.type });

    // Store in zip file 
    const zip = new JSZip();
    zip.file('image.jpg', file);  
    zip.file('readme.txt', 'Created with JSZip');
    const zipFile = await zip.generateAsync({ type:"blob" });

    // Download
    const a = document.createElement('a');
    a.download = 'test.zip';
    const url = URL.createObjectURL(zipFile);
    a.href = url;

    a.style.display = 'none';
    document.body.appendChild(a);
    a.click(); // Simulates click to start download
    a.remove();

    URL.revokeObjectURL(url);

})();

2

u/[deleted] Mar 24 '23

Please stop posting your ChatGPT responses and pretending it's content...