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 (15)
I hope you enjoy this discussion. In any case, I ask you to join it.
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!