splunk
splunk

Reputation: 6805

unexpected end of archive error when trying to open a Zip file downloaded via javascript

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

These are the response headers that I get if I try to call the API via Swagger:

 accept-ranges: bytes 
 access-control-allow-headers: Content-Disposition 
 cache-control: no-cache,no-store,max-age=0,must-revalidate 
 connection: keep-alive 
 content-disposition: attachment; filename="file1.zip" 
 content-length: 85259 
 content-type: application/octet-stream 
 date: Thu,20 Feb 2025 10:20:01 GMT 
 expires: 0 
 pragma: no-cache 
 vary: Origin,Access-Control-Request-Method,Access-Control-Request-Headers 

What am i doing wrong?

Upvotes: 0

Views: 35

Answers (0)

Related Questions