Learn how to quickly encode your file input content as Base64 Data URI and save it to your server

Uploading files using Base64 encoding is a common practice, the usage of the technique has been increased since React and Vue.js like frameworks gained popularity.
In this guide I'm going to show you how to upload files using base64 encoding
Base64 is a encoding algorithm that allows you to transform any characters into an alphabet which consists of Latin letters, digits, plus, and slash. You can convert images into a “readable” string, which can be saved or transferred anywhere.
To understand it better I recommend you to take a look at that wonderful article from base64.guru and What is Base64 Encoding by Akshay Kumar
We can't just send the Base64 string to our server and process it, what makes it different than any other string? How do you know the file is a image or PDF file? That's where Data URI comes in.
Data URI or Data URL is a format that we can use some data as an inline string. In order to process our Base64 data in server we need to know the mime type (which can be tricked), which Data URI format provides this.
This is the Data URI or Data URL format:
data:[<mime type>][;charset=<charset>][;base64],<encoded data>For example this a Base64 string wrapped as a Data URI:
<img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAoHCBUWFRgVFRYZGRgZHBgYGBwYGhgYGBoYGBgaGhoZGBgcIS4lHB4rIRgYJjgmKy8xNTU1GiQ7QDs0Py40NTEBDAwMEA8QHBISGjQh...3000 more characters" />The output:

Try it yourself! Choose a file and see base64 encoding of it.
Data (choose a file to see)
Wanna play with it? Use our CodeSandbox Example
Let's create a very simple form, we are going to handle it with Javascript
1<form id="formcarryForm">
2 <label for="nameInput">Name</label>
3 <input type="text" id="nameInput" />
4
5 <label for="messageInput">Message</label>
6 <textarea id="messageInput" cols="30" rows="2"></textarea>
7
8 <input type="file" id="pictureInput" />
9
10 <button type="submit">Submit</button>
11</form>Update 6 Jan, 2023:
We have built free form generator tool that you can customize and get HTML code, make sure you check it out if you need form template.
In order to upload files as Base64, we need to listen the change event of our file input, and the process is async so we need to hold some state to determinate whether we can submit the form or not.
Let's start with our file input.
1const fileInput = document.getElementById('pictureInput')
2
3// This is for storing the base64 strings
4let myFiles = {}
5// if you expect files by default, make this disabled
6// we will wait until the last file being processed
7let isFilesReady = true
8
9fileInput.addEventListener('change', async (event) => {
10 const files = event.srcElement.files;
11
12 console.log(files)
13})We are going to use isFilesReady later to check if the async process has been completed or not, it's true by default because there are no files in the input when the page loads, if you want to make it required you can change it to isFilesReady = false
Let's try what happens:
As you can see, we can access our files, now it's time for the fun part.
We are going to use native FileReader API to read files from the input
1fileInput.addEventListener('change', async (event) => {
2 // clean up earliest items
3 myFiles = {}
4 // set state of files to false until each of them is processed
5 isFilesReady = false
6
7 const files = event.srcElement.files;
8
9 const filePromises = Object.entries(files).map(item => {
10 return new Promise((resolve, reject) => {
11 const [index, file] = item
12 const reader = new FileReader();
13 reader.readAsBinaryString(file);
14
15 reader.onload = function(event) {
16 // handle reader success
17
18 resolve()
19 };
20
21 reader.onerror = function() {
22 console.log("couldn't read the file");
23 reject()
24 };
25 })
26 })
27
28 Promise.all(filePromises)
29 .then(() => {
30 // if each file processed successfuly then set our state to true
31 isFilesReady = true
32 })
33 .catch((error) => {
34 console.log(error)
35 console.log('something wrong happened')
36 })
37})Now we can access FileReader data using event.target.result but we need to transform it to Base64 string, let's do that:
1fileInput.addEventListener('change', async (event) => {
2 // clean up earliest files
3 myFiles = {}
4 // set state of files to false until each of them is processed
5 isFilesReady = false
6
7 const files = event.srcElement.files;
8
9 const filePromises = Object.entries(files).map(item => {
10 return new Promise((resolve, reject) => {
11 const [index, file] = item
12 const reader = new FileReader();
13 reader.readAsBinaryString(file);
14
15 reader.onload = function(event) {
16 // Convert file to Base64 string
17 // btoa is built int javascript function for base64 encoding
18 myFiles['picture'] = btoa(event.target.result)
19
20 resolve()
21 };
22 reader.onerror = function() {
23 console.log("can't read the file");
24 reject()
25 };
26 })
27 })
28
29 Promise.all(filePromises)
30 .then(() => {
31 console.log('ready to submit')
32 isFilesReady = true
33 })
34 .catch((error) => {
35 console.log(error)
36 console.log('something wrong happened')
37 })
38})So now we have converted our file to Base64 string and pushed it inside the myFiles object. every time our input get changes, myFiles is going to erase all the data it holds and will process everything again.
We have converted our files to Base64 string but that's not enough to upload files, we need to convert it to Data URI, it should look like this;
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAoHCBUWFRgVFRYZGRgZHBgYGBwYGhgYGBoYGBgaGhoZGBgcIS4lHB4rIRgYJjgmKy8xNTU1GiQ7QDs0Py40NTEBDAwMEA8QHBISGjQh...3000 more charactersThe format is;
data:[<mime type>][;charset=<charset>][;base64],<encoded data>Fortunately, we can access the MimeType, so that's going to be easy like that:
// Convert Base64 to data URI
// Assign it to your object
myFiles['picture'] = `data:${file.type};base64,${btoa(event.target.result)}`So now it's ready to upload. But let's make some tweaks before we go on.
I have named our file input as picture for the example, let's make our code dynamic so it can get the file input name attribute
// this is to get the input name attribute, in our case it will yield as "picture"
// I'm doing this because I want you to use this code dynamically
// so if you change the input name, the result also going to effect
const inputKey = fileInput.getAttribute('name')then change this;
myFiles[inputKey] = `data:${file.type};base64,${btoa(event.target.result)}`that way if you change your input name to resume it will yield as myFiles['resume']
Let's cover our code so it can support multiple file input;
<input type="file" id="pictureInput" multiple/>So in that case, we want to check if input has single or multiple files, if it has single file we want to name it right according to input name, in our example it would be picture but if it has more than one file, we are going to name with file lengths such as picture[0], picture[1]
here's the code:
+ // if it's multiple upload field then set the object key as picture[0], picture[1]
+ // otherwise just use picture
+ const fileKey = `${inputKey}${files.length > 1 ? `[${index}]` : ''}`
+ // Convert Base64 to data URI
+ // Assign it to your object
- myFiles[inputKey] = `data:${file.type};base64,${btoa(event.target.result)}`
+ myFiles[fileKey] = `data:${file.type};base64,${btoa(event.target.result)}`Let's cover our form submit event, what we want to do in that case is we will check if the files are ready, if they're not we are going to show an alert to user
1const formElement = document.getElementById('formcarryForm')
2
3const handleForm = async (event) => {
4 event.preventDefault();
5
6 if(!isFilesReady){
7 alert('files still getting processed')
8 }
9}
10
11formElement.addEventListener('submit', handleForm)All of the code we wrote so far should look like this;
1const fileInput = document.getElementById('pictureInput')
2
3// This is for storing the base64 strings
4let myFiles = {}
5// if you expect files by default, make this disabled
6// we will wait until the last file being processed
7let isFilesReady = true
8
9fileInput.addEventListener('change', async (event) => {
10 // clean up earliest items
11 myFiles = {}
12 // set state of files to false until each of them is processed
13 isFilesReady = false
14
15 // this is to get the input name attribute, in our case it will yield as "picture"
16 // I'm doing this because I want you to use this code dynamically
17 // so if you change the input name, the result also going to effect
18 const inputKey = fileInput.getAttribute('name')
19 var files = event.srcElement.files;
20
21 const filePromises = Object.entries(files).map(item => {
22 return new Promise((resolve, reject) => {
23 const [index, file] = item
24 const reader = new FileReader();
25 reader.readAsBinaryString(file);
26
27 reader.onload = function(event) {
28 // if it's multiple upload field then set the object key as picture[0], picture[1]
29 // otherwise just use picture
30 const fileKey = `${inputKey}${files.length > 1 ? `[${index}]` : ''}`
31 // Convert Base64 to data URI
32 // Assign it to your object
33 myFiles[fileKey] = `data:${file.type};base64,${btoa(event.target.result)}`
34
35 resolve()
36 };
37 reader.onerror = function() {
38 console.log("can't read the file");
39 reject()
40 };
41 })
42 })
43
44 Promise.all(filePromises)
45 .then(() => {
46 console.log('ready to submit')
47 isFilesReady = true
48 })
49 .catch((error) => {
50 console.log(error)
51 console.log('something wrong happened')
52 })
53})
54
55const formElement = document.getElementById('formcarryForm')
56
57const handleForm = async (event) => {
58 event.preventDefault();
59
60 if(!isFilesReady){
61 console.log('files still getting processed')
62 return
63 }
64}
65
66formElement.addEventListener('submit', handleForm)Let's create an object of our form values in the form submit event;
1const formElement = document.getElementById('formcarryForm')
2
3const handleForm = async (event) => {
4 event.preventDefault();
5
6 if(!isFilesReady){
7 console.log('files still getting processed')
8 return
9 }
10
11 const formData = new FormData(formElement)
12
13 // get name and message input from our <form> element
14 let data = {
15 'name': formData.get('name'),
16 'message': formData.get('message')
17 }
18
19 // iterate over the base64 files we've converted
20 Object.entries(myFiles).map(item => {
21 // destruct the file
22 const [key, file] = item
23 // append it to our data object
24 data[key] = file
25 })
26
27 console.log(data)
28}
29
30formElement.addEventListener('submit', handleForm)Let's try it out:
We've done all the necessary stuff on the front-end except network request part.
At formcarry we allow our customers to upload files as Base64 (pro feature).
You can either use our service to handle your form, or you can write a server code to process Base64 Data URI.
Luckily for you, I'm going to cover both of them.
Now we can send our data to formcarry, the important thing in this step is converting our object to JSON and setting the Content Type as application/json.
1const handleForm = async (event) => {
2 event.preventDefault();
3
4 if(!isFilesReady){
5 console.log('files still getting processed')
6 return
7 }
8
9 const formData = new FormData(formElement)
10
11 let data = {
12 'name': formData.get('name'),
13 'message': formData.get('message')
14 }
15
16 Object.entries(myFiles).map(item => {
17 const [key, file] = item
18 // append the file to data object
19 data[key] = file
20 })
21
22 fetch('https://formcarry.com/s/{Your-Unique-Endpoint}', {
23 method: 'POST',
24 body: JSON.stringify(data),
25 headers: {
26 'Content-Type': 'application/json',
27 Accept: 'application/json'
28 }
29 })
30 // convert response to json
31 .then(r => r.json())
32 .then(res => {
33 console.log(res);
34 });
35}Change https://formcarry.com/s/{Your-Unique-Endpoint} with your unique form ID
Submit your form by filling out all of the fields, then refresh your dashboard

formcarry will automagically convert your base64 to download-ready file.
I'm going to use Express.js for our example, let's create an express app using express-generator
$ npx express-generator Approximately Base64 files are 33% heavier than the original file, you might want to keep that in mind.
Now, let's allow our server to process large body data by getting into the app.js and change:
-app.use(express.json());
-app.use(express.urlencoded({ extended: false }));
+app.use(express.json({limit: '50mb'}));
+app.use(express.urlencoded({ extended: true, limit: '50mb' }));Also we need to enable CORS to perform request from our front-end app:
npm i --save corsEnable it like this:
var express = require('express');
var ba64 = require('ba64');
var cors = require('cors');
var app = express();
app.use(cors());I'm going to remove all the unnecessary stuff, you can replace this with your app.js:
1var createError = require('http-errors');
2var express = require('express');
3var path = require('path');
4var cors = require('cors')
5
6var app = express();
7
8app.use(cors());
9
10app.use(express.json({limit: '50mb'}));
11app.use(express.urlencoded({ extended: true, limit: '50mb' }));
12app.use(express.static(path.join(__dirname, 'public')));
13
14// catch 404 and forward to error handler
15app.use(function(req, res, next) {
16 next(createError(404));
17});
18
19// error handler
20app.use(function(err, req, res, next) {
21 // set locals, only providing error in development
22 res.locals.message = err.message;
23 res.locals.error = req.app.get('env') === 'development' ? err : {};
24
25 // render the error page
26 res.status(err.status || 500);
27 res.render('error');
28});
29
30module.exports = app;Now we need to create a Express route to process our form data.
But first we are going to use a tiny package called ba64 which will help us to save base64 images to our disk.
The flow should be like this;
That's where ba64 package comes in, it will automatically extract Base64 string from Data URI, and append the file extension after the file name automatically.
npm i --save ba64Import it in our app.js
var ba64 = require('ba64')Let's create our route, go to app.js and add following:
1app.post('/upload', async (req, res, next) => {
2 // exclude name and message for the sake of demo
3 // all other body items will be considered as a file
4 const { name, message, ...files } = req.body
5
6 for(let key in files){
7 const base64 = files[key]
8
9 // check if it's correctly formatted Base64 Data URI
10 if(checkBase64(base64)){
11 // Write it to our root directory using input key as filename
12 // eg. picture[1]
13 ba64.writeImageSync(key, base64)
14 }
15 }
16
17 res.send({files})
18})
19
20function checkBase64(string){
21 const B64_REGEX = /^data:.*;base64,([0-9a-zA-Z+\\/]{4})*(([0-9a-zA-Z+\\/]{2}==)|([0-9a-zA-Z+\\/]{3}=))?$/i
22
23 return B64_REGEX.test(string)
24}Final code should look like:
1var createError = require('http-errors');
2var express = require('express');
3var path = require('path');
4var ba64 = require('ba64')
5var cors = require('cors')
6
7var app = express();
8
9app.use(cors());
10
11// view engine setup
12app.use(express.json({limit: '50mb'}));
13app.use(express.urlencoded({ extended: true, limit: '50mb' }));
14app.use(express.static(path.join(__dirname, 'public')));
15
16
17app.post('/upload', async (req, res, next) => {
18 // exclude name and message for the sake of demo
19 // all other body items will be considered as a file
20 const { name, message, ...files } = req.body
21
22 for(let key in files){
23 const base64 = files[key]
24
25 // check if it's correctly formatted Base64 Data URI
26 if(checkBase64(base64)){
27 // Write it to our root directory using input key as filename
28 // eg. picture[1]
29 ba64.writeImageSync(key, base64)
30 }
31 }
32
33 res.send({files})
34})
35
36function checkBase64(string){
37 const B64_REGEX = /^data:.*;base64,([0-9a-zA-Z+\/]{4})*(([0-9a-zA-Z+\/]{2}==)|([0-9a-zA-Z+\/]{3}=))?$/i
38
39 return B64_REGEX.test(string)
40}
41
42// catch 404 and forward to error handler
43app.use(function(req, res, next) {
44 next(createError(404));
45});
46
47// error handler
48app.use(function(err, req, res, next) {
49 // set locals, only providing error in development
50 res.locals.message = err.message;
51 res.locals.error = req.app.get('env') === 'development' ? err : {};
52
53 // render the error page
54 res.status(err.status || 500);
55 res.render('error');
56});
57
58module.exports = app;Now run the app using:
$ npm startLet's get back to our front-end code and point our form to the back-end our server runs at http://localhost:3000 and our route is localhost:3000/upload
1const handleForm = async (event) => {
2 event.preventDefault();
3
4 if(!isFilesReady){
5 console.log('files still getting processed')
6 return
7 }
8
9 const formData = new FormData(formElement)
10
11 let data = {
12 'name': formData.get('name'),
13 'message': formData.get('message')
14 }
15
16 Object.entries(myFiles).map(item => {
17 const [key, file] = item
18 // append the file to data object
19 data[key] = file
20 })
21
22 fetch('http://localhost:3000/upload', {
23 method: 'POST',
24 body: JSON.stringify(data),
25 headers: {
26 'Content-Type': 'application/json',
27 Accept: 'application/json'
28 }
29 })
30 // convert response to json
31 .then(r => r.json())
32 .then(res => {
33 console.log(res);
34 });
35}Let's try it:
It works!
Thanks for following the blog post to the end, base64 is a tricky issue that's why I wanted to prepare an end-to-end fully functional tutorial.
I hope it's beneficial for you, if you have any questions just leave a comment and I'll try my best.
If you want to support us, just take a look at our service formcarry for a hassle free form handling.
Nusu Alabuga founded formcarry in 2017 and still runs it: the ingest pipeline, the spam filtering, the email delivery and the incident tracking that watches customers' forms. A product engineer by trade, with years of work in payments, security, invoicing and banking infrastructure.
WebsiteXLinkedInGitHub