I'm trying to convert blob to zip file. In result of actual code I'm getting zip file, but it is in wrong format, so I can't open it. Does anyone know how to convert blob to zip file in correct format without libraries on client side?
My actual code:
<input type="file" onchange="makeArchive(this.files)" value='files' multiple>
function makeArchive(files) {
const a = document.createElement('a');
const blob = new Blob([...files], {type: 'application/zip'});
a.href = URL.createObjectURL(blob);
a.download = `some.zip`;
a.click();
}
It is not possible to easily create a ZIP archive using JavaScript without any 3rd-party libraries.
The function in your example snipped is just concatenating the binary data of the files into one large blob. Specifying a MIME-type of application/zip has no effect on the encoding of the files and just tells JavaScript to treat the binary data like it was a ZIP file:
// Example data:
const a = new Uint16Array([1337]);
const b = new Uint16Array([42]);
// This just combines the data of a and b into one file:
const stillNotAZip = new Blob([a, b], { type: "application/zip" });
stillNotAZip.arrayBuffer().then(data => console.log(new Uint16Array(data)));
// Will output [1337, 42]
If you want to create an actual ZIP file without implementing the format yourself, you will have to resort to using a libraries like JSZip.