1

i have a string of image dataURL base 64.

i have follow How to convert Base64 String to javascript file object like as from file input form?

  function getFileFormat(url) {
  const arr = url.split(',');
  const mime = arr[0].match(/:(.*?);/)[1];
  const generateUUID = Math.floor(1000000000000000 + Math.random() * 9000000000000000);
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n > 0) {
    u8arr[n] = bstr.charCodeAt(n);
    n -= 1;
  }
  return new File([u8arr], generateUUID, { type: mime });
}

the value of this file is will be like this when consoled :

File {name: "9689093051172908", lastModified: 1578461450568, lastModifiedDate: Wed Jan 08 2020 13:30:50 GMT+0800 (Malaysia Time), webkitRelativePath: "", size: 65627, …}
name: "9689093051172908"
lastModified: 1578461450568
lastModifiedDate: Wed Jan 08 2020 13:30:50 GMT+0800 (Malaysia Time) {}
webkitRelativePath: ""
size: 65627
type: "image/png"
__proto__: File

it's success to send this file to the backend through post. but when preview this file, it's not an image, it'll be open a .txt file..

the post request are require me to send the file of an image into multipart data type and the image data i received is in base64 format. is there another way to convert my base64 string into a file form that represent an image? or is there any mistake in those code?

Khairul Habib
  • 452
  • 1
  • 12
  • 29

2 Answers2

0
function getFileFormat(url) {
  const byteString = atob(url.split(',')[1]);
  const mimeString = url.split(',')[0].split(':')[1].split(';')[0];
  const ab = new ArrayBuffer(byteString.length);
  const ia = new Uint8Array(ab);
  for (let i = 0; i < byteString.length; i += 1) {
    ia[i] = byteString.charCodeAt(i);
  }
  return new Blob([ab], { type: mimeString });
}

this is what i've done and it's worked. just shared if there is anyone also search for this function

Khairul Habib
  • 452
  • 1
  • 12
  • 29
-1
    const u8arr = new Uint8Array(n);
    while (n > 0) {
    u8arr[n-1] = bstr.charCodeAt(n-1);
    n -= 1;
    }
notme2020
  • 1
  • 2
  • 1
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – leopal Jan 08 '20 at 10:15