Problem with download file in Google Chrome

I encountered such a problem when I tried to download base64 decoded file with a size over 1mb in Chrome.

I had a function like this:


export const downloadBase64File = (fileData, fileName) => {

  const fileUrl = `data:application/octet-stream;base64,${fileData}`;

  const link = document.createElement('a');

  link.href = fileUrl;

  link.setAttribute('download', fileName);

  document.body.appendChild(link);

  link.click();

  link.remove();

};

It worked good in FireFox but didn't work in Google Chrome. And I found the following solution:


const urlToFile = (url, filename) => {

  return fetch(url)

    .then((res) => {

      return res.arrayBuffer();

    })

    .then((buf) => {

      return new File([buf], filename);

    });

};



export const downloadBase64File = (fileData, fileName) => {

  const fileUrl = `data:application/octet-stream;base64,${fileData}`;



  urlToFile(fileUrl, fileName).then((file) => {

    const blob = new Blob([file], { type: 'application/octet-stream' });

    const blobURL = window.URL.createObjectURL(blob);

    const link = document.createElement('a');

    link.href = blobURL;

    link.setAttribute('download', fileName);

    document.body.appendChild(link);

    link.click();

    link.remove();

  });

}

It works correctly for all browsers.

Do you have a project for us?Get a free quote