3

I am working on a project where I have to upload an image as form data along with other text fields. I have my file in Base64 string at first, then I convert it into a file before uploading it to the server.

const data = await fetch(base64String);
const blob = await data.blob();
const file = await new File([blob], 'avatar', { type: 'image/png' });

I logged the base64String in the client side before uploading it to the server. Then I upload file to the server as a File. Before saving it to MongoDB when I log it as a base64 string again in the server side, I see my string is not the same as before. I feel like while converting the base64 to file in the client side I am doing something wrong. Help me out please.

asif.ibtihaj
  • 361
  • 5
  • 14
  • I had a similar with PHP. I found out that the base64 string changed during from Front-end to server, because some characters such as spaces or plus were modified – Gogu Gogugogu Jul 04 '21 at 20:35
  • 2
    Check whether this might help you: https://stackoverflow.com/questions/38658654/how-to-convert-a-base64-string-into-a-file/38659875 – Shantanu Bharatia Jul 04 '21 at 20:36
  • If your intention is to upload as a `File` to the server, where is it that you're un-encoding from base64? It looks like you're passing the still-encoded data to a `Blob`, and then making a file from that. You should unencode using the global `atob()` function, or load the base64 data as a data URI. – stephancasas Jul 04 '21 at 20:48

1 Answers1

5

I have figured out my problem. When I take image file input from my computer I get a base64 string like below -

dataimage/jpegbase64/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAA...

But, when I convert it back into a file it expects a string like below -

/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAA....

So, basically, I had to trim the string accordingly to match the expected format and wrote a base64 to file conversion function following this answer. Here is my function to convert a base64 string to an image file

export function getFileFromBase64(string64:string, fileName:string) {
  const trimmedString = string64.replace('dataimage/jpegbase64', '');
  const imageContent = atob(trimmedString);
  const buffer = new ArrayBuffer(imageContent.length);
  const view = new Uint8Array(buffer);

  for (let n = 0; n < imageContent.length; n++) {
    view[n] = imageContent.charCodeAt(n);
  }
  const type = 'image/jpeg';
  const blob = new Blob([buffer], { type });
  return new File([blob], fileName, { lastModified: new Date().getTime(), type });
}
asif.ibtihaj
  • 361
  • 5
  • 14