I’m trying to download a ZIP file from a backend API that returns the ZIP binary as a string.
If I do this:
curl --location 'https://backend-endpoint.com/get-file' >> test.zip
it creates a ZIP file containing a couple of files that I can extract and open correctly.
On the frontend side I have a button that, if clicked, calls the following code that should download the ZIP file after the backend API call:
const convertBinaryToBlob = (binary: string, contentType: string): Blob => {
// Convert the binary string to a byte array
const binaryLen = binary.length;
const bytes = new Uint8Array(binaryLen);
for (let i = 0; i < binaryLen; i++) {
bytes[i] = binary.charCodeAt(i);
}
const blob = new Blob([bytes], { type: contentType });
return blob;
};
clientAPI.getFile().then((resp) => {
if (resp.status === 200) {
let blobContent = convertBinaryToBlob(resp.data, 'application/zip');
const href = URL.createObjectURL(blobContent);
const link = document.createElement('a');
link.href = href;
link.setAttribute('download', 'test.zip');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(href);
}
});
When I click the button a ZIP file is downloaded but it seems corrupt because If I try opening it I get the following error: unexpected end of archive
What am i doing wrong?