0

I have created a React app that allows users to add images to the cart. Each image is contained in the { cartItems } array which is controlled using Redux. When the user clicks the button, I want a zip file generated with all the images that are in the cart. I think I should be using the jszip library, but can't seem to figure it out. Below is a snippet of my code.

import React, { useState } from 'react'
import { useSelector } from 'react-redux'
import { motion } from 'framer-motion'
import JSZip from 'jszip'

export default function Cart() {
  const { cartItems } = useSelector((state) => state.cart)

  const handleZipDownload = () => {

  }

  return (
      <div className='pt-16 relative px-12' id='grid-container'>
        <h1 className='text-5xl mb-16 text-center' id='grid-header'>
          Shopping Cart
        </h1>
        <button onClick={handleZipDownload}>download images</button>
      </div
     )
maxheezy's
  • 53
  • 4
  • 1
    You can't do things like that in React. React is in fact just JS that runs in the browser env, so it doesn't have the ability to read and write files directly to your disk. You can however do this with nodeJS or other server-side languages like Python or C# but you will first need to send your images to the backend services – Joshua Feb 07 '23 at 02:17
  • 1
    @konekoya it doesn't have access to filesystem but it's perfectly capable of creating files and prompting user to download them :) https://developer.mozilla.org/en-US/docs/Web/API/File – ihor.eth Feb 07 '23 at 03:51
  • maxheezy's pls accept if the answer helped you. – ihor.eth Feb 23 '23 at 17:50

1 Answers1

-1

It's doable, I did the same for some .json files.

import JSZip from 'jszip'
import { saveAs } from 'file-saver'

const { cartItems } = useSelector((state) => state.cart)

const handleZipDownload = async () => {
  const zip = new JSZip()
  cartItems.forEach(img => {
    zip.file(img.name, imgData, { base64: true });
  })
  const zipped = await zip.generateAsync(
  {
    type: 'blob',
    comment: 'Optional comment for example your website URL',
  })
  saveAs(zipped, 'archive file name')
}

You just need to figure out how to pass imgData depending on how you save/access images in the cart. You most likely have their URLs, in that case use fetch() get the image blob then use it here. If you do end up passing blob as 2nd argument of zip.file then as 3rd argument pass

{ binary: true }

See more https://stackoverflow.com/a/50248437/8833279 https://stuk.github.io/jszip/documentation/api_jszip/file_data.html

ihor.eth
  • 2,207
  • 20
  • 27