A virtual teacher who reveals to you the great secrets of Base64

Encode form file to Base64 in JavaScript

If you have a web page where you allow users to upload files, then you probably have a <input type="file" /> element. Typically, you get the contents of the file when the user submits the form. However, JavaScript allows you to get it immediately after the user has selected the file (for example, it is useful if you want to show the image preview).

Below I provide an example of how to encode the contents of a file to Base64 as soon as the user has selected it from his device (i.e. before upload it to server). The example is supported by most popular browsers (Chrome 13+, Edge 12+, Firefox 3.6+, Internet Explorer 10+, Safari 6+).

// Be aware! We are handling only the first <input type="file" /> element
// To avoid errors, it should be placed before this piece of code
var input = document.querySelector('input[type=file]');

// You will receive the Base64 value every time a user selects a file from his device
// As an example I selected a one-pixel red dot GIF file from my computer
input.onchange = function () {
  var file = input.files[0],
    reader = new FileReader();

  reader.onloadend = function () {
    // Since it contains the Data URI, we should remove the prefix and keep only Base64 string
    var b64 = reader.result.replace(/^data:.+;base64,/, '');
    console.log(b64); //-> "R0lGODdhAQABAPAAAP8AAAAAACwAAAAAAQABAAACAkQBADs="
  };

  reader.readAsDataURL(file);
};

Another way to convert form file to Base64 is to call reader.readAsBinaryString(blob) and use btoa(reader.result) to get the Base64 string. However, this method will most likely work slower and is not supported by Internet Explorer at all.

Comments (4)

I hope you enjoy this discussion. In any case, I ask you to join it.

  • alireza,
    If you submit reader.result as content it will send base64 data + file type at the beginning. This will work for those who get zero sized files on the server.
  • Pankaj,
    Thank you very much
  • Camilo,
    malo tu turorial culiao feo
  • igor,
    Good day ! I have this code:

    import React from 'react';
    import { makeStyles } from '@material-ui/core/styles';
    import Button from '@material-ui/core/Button';
    const useStyles = makeStyles((theme) => ({
    root: {
    '& > *': {
    margin: theme.spacing(1),
    },
    },
    input: {
    display: 'none',
    },
    }));

    export default function UploadButtons() {
    const classes = useStyles();

    return (
    <div className={classes.root}>
    <input
    accept="image/*"
    className={classes.input}
    id="contained-button-file"
    multiple
    type="file"
    />
    <label htmlFor="contained-button-file">
    <Button variant="contained" color="primary" component="span">
    Upload
    </Button>
    </label>

    </div>
    );
    }

    How can I use your code in mine? To encode a picture. Thank you in advance!
Add new comment

If you have any questions, remarks, need help, or just like this page, please feel free to let me know by leaving a comment using the form bellow.
I will be happy to read every comment and, if necessary, I will do my best to respond as quickly as possible. Of course, spammers are welcome only as readers.