0

I have a dataURL string of an image that i need to post to a server, the server only accepts raw file format so i have to find a way to convert it. I have seen some answers that suggest using a blob but that wouldn't work since it has to be a File.

I have tried this function but the server is throwing a bad request when i use the resulting file.

function dataURLtoFile(dataURL, filename) {
  const [mime, base64] = dataURL.split(';base64,');

  const binaryData = atob(base64);

  const arrayBuffer = new ArrayBuffer(binaryData.length);
  const uint8Array = new Uint8Array(arrayBuffer);
  for (let i = 0; i < binaryData.length; i++) {
    uint8Array[i] = binaryData.charCodeAt(i);
  }

  const blob = new Blob([uint8Array], { type: mime });

  return new File([blob], filename, { type: mime });
}
isherwood
  • 58,414
  • 16
  • 114
  • 157

0 Answers0