Categories
JavaScript Answers

How to convert base64 string to JavaScript file object like as from file input form?

Spread the love

To convert a Base64 string to a JavaScript File object, we can follow these steps:

  1. Convert the Base64 string to a Blob object.
  2. Create a new File object from the Blob.

For example, we write:

function base64toFile(base64String, filename, mimeType) {
    // Convert the Base64 string to a Blob
    const byteCharacters = atob(base64String);
    const byteArrays = [];
    for (let offset = 0; offset < byteCharacters.length; offset += 512) {
        const slice = byteCharacters.slice(offset, offset + 512);
        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: mimeType });

    // Create a new File object
    const file = new File([blob], filename, { type: mimeType });
    
    return file;
}

// Example usage:
const base64String = '...'; // Your Base64 string here
const filename = 'example.txt'; // Desired filename
const mimeType = 'text/plain'; // MIME type of the file

const file = base64toFile(base64String, filename, mimeType);

// Now you can use the 'file' object as you would with a file from an input form
console.log(file);

In this code, the base64toFile function takes the Base64 string, filename, and MIME type as input parameters.

It first converts the Base64 string to a Blob using the atob() function.

Then, it creates a new File object from the Blob with the specified filename and MIME type.

Finally, it returns the File object.

You can now use the file object like any other File object, such as uploading it to a server or manipulating it in your JavaScript code.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *