Reputation: 398
I need to encode a PDF file to Base64 with Javascript. I can create Base64-encoded jpeg or png images in Javascript, but I could not find any way or sample code to create a Base64-encoded string from a PDF file.
Is it there any solution using a HTML5 canvas?
Thanks.
Upvotes: 33
Views: 137085
Reputation: 924
function Selectfile() {
document.getElementById('fileInput').click();
};
function handleFileSelect (event) {
var selectedFile = event.target.files[0];
if (selectedFile) {
var reader = new FileReader();
reader.onload = function (event) {
var selectedFile = selectedFile;
// Convert the file to Base64
var selectedFileBase64 = event.target.result.split(',')[1];
console.log(selectedFileBase64);
};
reader.readAsDataURL(selectedFile);
}
};
document.getElementById('fileInput').addEventListener('change', handleFileSelect);
<button onclick="Selectfile()">Browse</button>
<input type="file" id="fileInput" style="display: none;"/>
Upvotes: -1
Reputation: 591
Try this :-
<input id="inputFile" type="file" onchange="convertToBase64();" />
<script type="text/javascript">
function convertToBase64() {
//Read File
var selectedFile = document.getElementById("inputFile").files;
//Check File is not Empty
if (selectedFile.length > 0) {
// Select the very first file from list
var fileToLoad = selectedFile[0];
// FileReader function for read the file.
var fileReader = new FileReader();
var base64;
// Onload of file read the file content
fileReader.onload = function(fileLoadedEvent) {
base64 = fileLoadedEvent.target.result;
// Print data in console
console.log(base64);
};
// Convert data to base64
fileReader.readAsDataURL(fileToLoad);
}
}
</script>
Upvotes: 45
Reputation:
Here is how one person did it:
Here is a link that suggests several other possible solutions:
Upvotes: 2