-1

how convert a base64 string image to blob image to send to backend by a form

some solution like this not worked for me

const b64toBlob = (b64Data, contentType='', sliceSize=512) => {
  const byteCharacters = atob(b64Data);
  const byteArrays = [];

  for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    const slice = byteCharacters.slice(offset, offset + sliceSize);

    const byteNumbers = new Array(slice.length);
    for (let i = 0; i < slice.length; i++) {
      byteNumbers[i] = slice.charCodeAt(i);
    }

    const byteArray = new Uint8Array(byteNumbers);
    byteArrays.push(byteArray);
  }

  const blob = new Blob(byteArrays, {type: contentType});
  return blob;
}
  • Assuming you copied that snippet from [this previous StackOverflow question](https://stackoverflow.com/q/16245767/21146235), there are comments on that answer that suggest it has some failure modes. There are also several other answers to that same question which provide alternatives, perhaps you could try those. – motto Apr 15 '23 at 21:24
  • yes. that was old pain. and now i guse finded good and clean solution maybe! that is closed and i cant send new answer so create this – saeed latifi Apr 15 '23 at 21:30

1 Answers1

0

i found a solution finaly with some cleaning be like this

export default async function base64ToBlob(dataUrl: string): Promise<Blob> {
let newImage = new Image();
return new Promise((resolve, reject) => {
    newImage.onload = () => {
        const canvas = document.createElement("canvas");
        canvas.width = newImage.width;
        canvas.height = newImage.height;
        const ctx = canvas.getContext("2d");
        ctx?.drawImage(newImage, 0, 0);
        canvas.toBlob(
            (blob: Blob | null) => {
                if (blob) resolve(blob);
                else reject;
            },
            "image/jpeg",
            1
        );
    };
    newImage.onerror = reject;
    newImage.src = dataUrl;
});

}

and use like this

const blob = await base64ToBlob(myBase64);
const form = new FormData();
form.append("image", blob);
const { data } = await HTTPService.post("someurl/image", form);