To make zip file of images and download it, which is stored in state variable first we need to install one dependencies,
Step 1 -- Install JSZIP using npm :
npm i jszip
Step 2 -- then import it inside our JSX file and make instance of it :
import { useState, useCallback } from "react";
import JSZip from "jszip";
export default Download(){
const [images,setImages]=useState([ // Array of images
"image1.jpg",
"image2.jpg",
"image3.jpg",
"image4.jpg",
"image5.jpg",
])
const zip = new JSZip(); // instance of JSZip
return (
<div>
<button onClick={handleDownload}>Download</button>
</div>
)
}
in above code we make one array state variable for store the images if you get this images from server then you use setImages to store images inside state.
Step 3(Final step) -- Write function to make zip of images and download it.
import { useState, useCallback } from "react";
import JSZip from "jszip";
export default Download(){
const [images,setImages]=useState([ // Array of images
"image1.jpg",
"image2.jpg",
"image3.jpg",
"image4.jpg",
"image5.jpg",
])
const zip = new JSZip(); // instance of JSZip
// Function for make zip file and download it
async function handleZip(){
// Add Images to the zip file
for (var i = 0; i < images.length; i++) {
const response = await fetch(images[i]);
const blob = await response.blob();
console.log(blob);
zip.file(images[i].split("/").pop(), blob);
if (i == selectedImages.length - 1) {
// Generate the zip file
const zipData = await zip.generateAsync({
type: "blob",
streamFiles: true,
});
console.log(zipData);
// Create a download link for the zip file
const link = document.createElement("a");
link.href = window.URL.createObjectURL(zipData);
link.download = "snapcial-ai.zip";
link.click();
}
}
return (
<div>
<button onClick={handleDownload}>Download</button>
</div>
)
}
Tadaaaa if it is helpful for you then follow me on linkedin :
Jaydeep Khachariya
if you face any errors then contact me on : khachariyajaydeep@gmail.com this email id.
Top comments (5)
Let me put it in a more understandable form
useDownload.js
component.js
I am facing a similar issue, but I want to get images from Unsplash. Anyway, where does the
selectedImages
array comes from?Have you tested this code?
I tested and use it for my project also, selectImages array is state variable which is i use for store images my images came from backend.
may I know how to unzip and get them images
Can you explain you doubt little bit l