Categories
JavaScript Answers

How to download file from bytes in JavaScript?

Spread the love

Sometimes, we want to download file from bytes in JavaScript.

In this article, we’ll look at how to download file from bytes in JavaScript.

How to download file from bytes in JavaScript?

To download file from bytes in JavaScript, we can create an object URL from a blob and then download with the URL.

For instance, we write

const base64ToArrayBuffer = (base64) => {
  const binaryString = window.atob(base64);
  const binaryLen = binaryString.length;
  const bytes = new Uint8Array(binaryLen);
  for (let i = 0; i < binaryLen; i++) {
    const ascii = binaryString.charCodeAt(i);
    bytes[i] = ascii;
  }
  return bytes;
};

const saveByteArray = (fileName, byte) => {
  const blob = new Blob([byte], { type: "application/pdf" });
  const link = document.createElement("a");
  link.href = window.URL.createObjectURL(blob);
  link.download = fileName;
  link.click();
};

const sampleArr = base64ToArrayBuffer(data);
saveByteArray("Sample Report.pdf", sampleArr);

to define the base64ToArrayBuffer function.

In it, we take the base64 string and convert it to the bytes array.

We call window.atob to convert the base64 string to a byte string.

And then we create the bytes array from the binaryString by using a for loop to get the characters with charCodeAt.

Next, we define the saveByteArray function that takes the fileName and byte array object.

In it, we create a blob from byte with the Blob constructor.

We set the type property to the MIME type of the downloaded file.

Then we create an a element with createElement.

And then we call window.URL.createObjectURL with blob to create an object URL and set it as the value of href.

We set the download property to fileName.

Then we call click to start the download.

Conclusion

To download file from bytes in JavaScript, we can create an object URL from a blob and then download with the URL.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.