1

I am receiving an excel file from an api call and need to save it to the user's computer. I have been trying to do this by creating a blob from it and downloading that, but for some reason the blob converts the binary data to a string somewhere in the process and then saves the binary of the string.

The function I am using is

function saveFile(raw)
{
    var excel = new Blob([raw], {type: mimeType});

    const data = const data = window.URL.createObjectURL(newBlob);
    var link = document.createElement('a');
    link.href = data;
    link.download="transactions.xlsx";
    link.click();
    setTimeout(function()
    {
        // For Firefox it is necessary to delay revoking the ObjectURL
        window.URL.revokeObjectURL(data);
    }, 100);
}

and I have tried both "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" and "octet/stream" for mimeType.

The result either way is that the first several bytes of the correct file are

50 45 03 04 14 00 08 08

which is displayed as "PK......" in a hex editor, whereas the first several bytes of what I am getting from my function are

50 4B 5C 75 30 30 30 33 5C 75 30 30 30 34

which is displayed as "PK\u0003\u0004"

At first I thought it was an error in how the data was being transmitted as the type header of the return was "application/json", but when I wrote a function to step through the response byte by byte to "fix" it being a string I found that prior to creating the blob that data was correct. Am I missing something about using blobs?

  • From the snippet you've attached it seems that you don't actually set the mime type... – Alon Bar Oct 14 '19 at 15:47
  • Also, you may not need to do anything with the rawData, just call `createObjectURL` directly on it. – Alon Bar Oct 14 '19 at 15:50
  • In my actual code instead of it being ```new Blob([raw], {type: mimeType});``` it is either ```new Blob([raw], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});``` or ```new Blob([raw], {type: "octet/stream"});``` – Denis Zdanovsky Oct 14 '19 at 15:53
  • Don't know if it changes anything but most examples here: (the SO question where I learned how to do it from) https://stackoverflow.com/questions/19327749/javascript-blob-filename-without-link attach the link element to the body before clicking it. – Alon Bar Oct 14 '19 at 16:00

0 Answers0