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

Viewed 249009

I want to convert Base64String extracted from file(ex: "AAAAA....~") to a javascript file object.

The javascript file object what I mean is like this code:

HTML:

<input type="file" id="selectFile" > 

JS:

$('#selectFile').on('change', function(e) {
  var file = e.target.files[0];

  console.log(file)
}

'file' variable is a javascript file object. So I want to convert a base64 string to the javascript file object like that.

I just want to get file object by decoding base64 string (encoded by other app from a file) without html file input form.

Thank you.

9 Answers
const url = 'data:image/png;base6....';
fetch(url)
  .then(res => res.blob())
  .then(blob => {
    const file = new File([blob], "File name",{ type: "image/png" })
  })

Base64 String -> Blob -> File.

This is the latest async/await pattern solution.

export async function dataUrlToFile(dataUrl: string, fileName: string): Promise<File> {

    const res: Response = await fetch(dataUrl);
    const blob: Blob = await res.blob();
    return new File([blob], fileName, { type: 'image/png' });
}

I had a very similar requirement (importing a base64 encoded image from an external xml import file. After using xml2json-light library to convert to a json object, I was able to leverage insight from cuixiping's answer above to convert the incoming b64 encoded image to a file object.

const imgName = incomingImage['FileName'];
const imgExt = imgName.split('.').pop();
let mimeType = 'image/png';
if (imgExt.toLowerCase() !== 'png') {
    mimeType = 'image/jpeg';
}
const imgB64 = incomingImage['_@ttribute'];
const bstr = atob(imgB64);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while (n--) {
  u8arr[n] = bstr.charCodeAt(n);
}
const file = new File([u8arr], imgName, {type: mimeType});

My incoming json object had two properties after conversion by xml2json-light: FileName and _@ttribute (which was b64 image data contained in the body of the incoming element.) I needed to generate the mime-type based on the incoming FileName extension. Once I had all the pieces extracted/referenced from the json object, it was a simple task (using cuixiping's supplied code reference) to generate the new File object which was completely compatible with my existing classes that expected a file object generated from the browser element.

Hope this helps connects the dots for others.

const file = new File([
  new Blob(["decoded_base64_String"])
], "output_file_name");

You could use a lib like this to decode and encode base64 to arrayBuffer.

Here is the Typescript version of accepted answer above by @cuixiping, now using Buffer instead of atob()

I saw deprecation warnings using atob() from TypeScript, although it isn't fully deprecated. Only one overload is. However, I converted mine to use the deprecation warning suggestion of Buffer. It seems more clean since it requires no extra loop to convert each character.

  /***
   * Converts a dataUrl base64 image string into a File byte array
   * dataUrl example:
   * data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIsAAACLCAYAAABRGWr/AAAAAXNSR0IA...etc
   */
  dataUrlToFile(dataUrl: string, filename: string): File | undefined {
    const arr = dataUrl.split(',');
    if (arr.length < 2) { return undefined; }
    const mimeArr = arr[0].match(/:(.*?);/);
    if (!mimeArr || mimeArr.length < 2) { return undefined; }
    const mime = mimeArr[1];
    const buff = Buffer.from(arr[1], 'base64');
    return new File([buff], filename, {type:mime});
  }

at the top of the file you'll need an import to make the typings happy.

import { Buffer } from 'buffer';

No special npm packages are needed.

Fast, Clean & Multi Purpose Method (Any Base64 File String to a File Object)

This method is developed for you, specially, for a fast multipurpose convert any base64 file string to a File object.

The Method:

// An example of base64 file string will look like this but with much longer base64 strings:
// let fileBase64Array = ['data:image/png;base64,ab...', 'data:image/png;base64,yz...'];

let convertedFiles = fileBase64Array.map((fileBase64, index) => {
  let fileType = fileBase64.substring(
    fileBase64.indexOf(":") + 1,
    fileBase64.lastIndexOf(";")
  );
  let fileExtension = fileType.split('/');
  return new File([fileBase64], `file${index}.${fileExtension[1]}`, {type: fileType});
});
console.log(convertedFiles);

The How (how this works):

This method uses creation of a File object with dynamic File Type and file extension setting.

Pros:

  • This method can be used for any file
  • Ready out of the box, just Copy/Past and Use!
  • Works on JS, not just NodeJS
  • Supports multiple File Types

This method supports all these file types and more:

  1. image/apng: Animated Portable Network Graphics (APNG)
  2. image/avif: AV1 Image File Format (AVIF)
  3. image/gif: Graphics Interchange Format (GIF)
  4. image/jpeg: Joint Photographic Expert Group image (JPEG)
  5. image/png: Portable Network Graphics (PNG)
  6. image/svg+xml: Scalable Vector Graphics (SVG)
  7. image/webp: Web Picture format (WEBP)

Bonus (Suppose you know the file type, and you want the method to be short with minimum code):

// An example of base64 file string will look like this but with much longer base64 strings:
// let fileBase64Array = ['data:image/png;base64,ab...', 'data:image/png;base64,yz...'];
let images = imagesBase.map((imageBase, index) => {
  return new File([imageBase], `image${index}.png`, {type: 'image/png'});
});

If you find this useful, please vote, this allows me to create new and improved content.

Complete Version for Typescript

async uploadImage(b64img: string) {
  var file = await this.urltoFile(b64img,'name.png',this.base64MimeType(b64img));
}

//return a promise that resolves with a File instance
urltoFile(url, filename, mimeType){
    return (fetch(url)
        .then(function(res){return res.arrayBuffer();})
        .then(function(buf){return new File([buf], filename,{type:mimeType});})
    );
}

//return mime Type of bs64
base64MimeType(encoded) {
    var result = null;
  
    if (typeof encoded !== 'string') {
      return result;
    }
  
    var mime = encoded.match(/data:([a-zA-Z0-9]+\/[a-zA-Z0-9-.+]+).*,.*/);
  
    if (mime && mime.length) {
      result = mime[1];
    }
  
    return result;
}

Thats Work for me Converting base64 Image to File

Related