Whenever I try to create a zip file using JSZip, I either get an error indicating the images may not be an instance of Blob (they are) or the result is corrupted/cannot be extracted.
I have a back-end API which returns a .png image given an id corresponding to the image from an authenticated endpoint.
In a server component, I obtain a set of image ids from a separate endpoint, then map it to an array of .png images (as Blob objects, using await res.blob()
). Then I create a zip file from these images using JSZip, which I return as a Buffer object.
In a client component, I receive this Buffer object, create a Blob object from it, then an URL which I click.
The server component:
const download = async (file, format: string) => {
"use server"
const imageArray = await makeImageArray(file.id, format);
const zip = new JSZip();
await Promise.all(imageArray.map(async (rendered) => {
console.log("blob", rendered.data)
zip.file(`${rendered.name.replaceAll(" ", "_")}.${rendered.type}`, Buffer.from(await rendered.data.arrayBuffer()).toString("base64"), {base64: true});
return rendered.data;
}));
const zipped = await zip.generateAsync({type: "blob"})
const arrayBuffer = await zipped.arrayBuffer();
const buffer = Buffer.from(arrayBuffer)
return buffer
}
The client component:
const clickAZip = async (file, format) => {
const a = document.createElement("a");
const zip = await onDownload(file, format)
a.href = URL.createObjectURL(new Blob(zip,{type: 'application/zip'}))
a.download=`${file.name}.zip`
a.click()
}
LucasL is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.