Want to become a Vibe Coder? Join Vibe Coding Training here
x
C# Corner
Tech
News
Videos
Forums
Jobs
Books
Events
More
Interviews
Live
Learn
Training
Career
Members
Blogs
Challenges
Certification
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Refer
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
Convert File into base64 in JavaScript using FileAPI
WhatsApp
Ashish Vishwakarma
Nov 02
2015
12.3
k
0
0
Since the File API is introduced in HTML5, we have ability to access and modify files pragramaticaly in JavaScript , here is an example of select a file using input tag and converting this binary file into base64 format.
<input type=
"file"
id=
"files"
name=
"files"
/>
<br/>
<textarea id=
"base64"
rows=
"5"
></textarea>
Checkout working example
@ http://codepen.io/AshishVishwakarma/pen/pjodjV.
// Check for the File API support.
if
(window.File && window.FileReader && window.FileList && window.Blob)
{
document.getElementById(
'files'
)
.addEventListener(
'change'
, handleFileSelect,
false
);
}
else
{
alert(
'The File APIs are not fully supported in this browser.'
);
}
function handleFileSelect(evt)
{
var f = evt.target.files[0];
// FileList object
var reader =
new
FileReader();
// Closure to capture the file information.
reader.onload = (function (theFile)
{
return
function (e)
{
var binaryData = e.target.result;
//Converting Binary Data to base 64
var base64String = window.btoa(binaryData);
//showing file converted to base64
document.getElementById(
'base64'
)
.value = base64String;
alert(
'File converted to base64 successfuly!\nCheck in Textarea'
);
};
})(f);
// Read in the image file as a data URL.
reader.readAsBinaryString(f);
}
base64
HTML5
FileAPI
JavaScript
Up Next
Convert File into base64 in JavaScript using FileAPI