How to get Base64 from an input file type:pdf?. i´m trying convert a file .pdf in string base64 with JavaScript.
Example:
var base64 = funtionconvertBase64(file);
function funtionconvertBase64(file){
....
....
return stringbase64
}
You have to load the file using the FileReader.
<input id="loadFile" type="file" onchange="readAsBase64()" />
<script type="text/javascript">
function readAsBase64() {
var files = document.getElementById("loadFile").files;
if (files.length > 0) {
var fileToLoad = files[0];
var fileReader = new FileReader();
var base64File;
// Reading file content when it's loaded
fileReader.onload = function(event) {
base64File = event.target.result;
// base64File console
console.log(base64File);
};
// Convert data to base64
fileReader.readAsDataURL(fileToLoad);
}
}
</script>
Related
if I upload 3 items with the file name: png1, png2, png3 Result will
be like this.
alert 1
png1 / base64 string convertion
alert 2
png2 / base64 string convertion
alert 3
png3 / base64 string convertion
I tried this code.
function readFile() {
var input = document.getElementById('gallery-photo-add');
var nameOfFile = "";
for (var i = 0; i < input.files.length; ++i) {
nameOfFile = input.files.item(i).name;
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.addEventListener("load", function (e) {
alert(nameOfFile);
alert(e.target.result);
});
reader.readAsDataURL(this.files[0]);
}
}
}
document.getElementById("gallery-photo-add").addEventListener("change", readFile);
<input type="file" multiple id="gallery-photo-add" style="overflow: auto;">
Try using + operation to display filename and base64 toghther in one alert.
Here is the reference to read more about JS operators
Edit: You want to alert and base64 togther which is not simple straight forward as base64 comes from FileReader API and filename is from input
I have wrapped your base64 and alert in function and also have simplified the JS code your to call the function onchange
Working Demo: https://jsfiddle.net/usmanmunir/hpej8f6o/
Run snippet below to see it working.
function readFile(input) {
//Store file name
var filesName = []
//Get total files
var filesTotal = input.files.length;
for (var i = 0; i < filesTotal; ++i) {
//Store file names
filesName.push(input.files.item(i).name)
var reader = new FileReader();
//Display alert and base64
function displayAlert(i) {
reader.addEventListener("load", function(e) {
alert(filesName[i] + ' Base64 ' + e.target.result);
})
}
reader.readAsDataURL(input.files[i]);
//Display Alerts
displayAlert(i)
}
}
<input type="file" multiple id="gallery-photo-add" onchange="readFile(this)" style="overflow: auto;">
Here are the jquery codes that i've written
$(function(){
// Prepare the preview for profile picture
$("#profile_image").change(function(){
$("#message").empty(); // To remove the previous error message
var file = this.files[0];
var imagefile = file.type;
var match= ["image/jpeg","image/png","image/jpg"];
if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2])))
{
$('#wizardPicturePreview1').attr('src','/images/houses/default.png');
$("#message").html("<p id='error'>Please Select A valid Image File</p>"+"<h4>Note</h4>"+"<span id='error_message'>Only jpeg, jpg and png Images type allowed</span>");
return false;
}
else
{
var reader = new FileReader();
reader.onload = function (e) {
$('#wizardPicturePreview1').attr('src', e.target.result).fadeIn('slow');
//getting the base64 string of the uploaded image
var imageso = e.target.result;
console.log('Encoded image:', imageso);
};
reader.readAsDataURL(this.files[0]);
}
});
$('form').submit(function() {
// submit the encoded base64 string of the uploaded image
$('.hidden-image-data').val(imageso);
var formValue = $(this).serialize();
$('#result-data').text(formValue);
// Prevent the form from actually submitting
return true;
});
});
I am getting the encoded image in console with the imageso variable in the change() function but it is nullable In the submit() function, the console tells me that the imageso variable is not declared while it is already declared. The problem is, how to get that base64 string of the uploaded image in the submit funtion using only JQuery without using Ajax?
imageso is outside the scope of the submit handler, you won't be able to access the variable as a result.
You will have to bring imageso into the submit scope.
I'd recommend to try and store it in the sessionStorage:
$(function(){
// Prepare the preview for profile picture
$("#profile_image").change(function(){
$("#message").empty(); // To remove the previous error message
var file = this.files[0];
var imagefile = file.type;
var match= ["image/jpeg","image/png","image/jpg"];
if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2])))
{
$('#wizardPicturePreview1').attr('src','/images/houses/default.png');
$("#message").html("<p id='error'>Please Select A valid Image File</p>"+"<h4>Note</h4>"+"<span id='error_message'>Only jpeg, jpg and png Images type allowed</span>");
return false;
}
else
{
var reader = new FileReader();
reader.onload = function (e) {
$('#wizardPicturePreview1').attr('src', e.target.result).fadeIn('slow');
//getting the base64 string of the uploaded image
var imageso = e.target.result;
sessionStorage.setItem("imageso", imageso);
console.log('Encoded image:', imageso);
};
reader.readAsDataURL(this.files[0]);
}
});
$('form').submit(function() {
// submit the encoded base64 string of the uploaded image
$('.hidden-image-data').val(sessionStorage.getItem("imageso"));
var formValue = $(this).serialize();
$('#result-data').text(formValue);
// Prevent the form from actually submitting
return true;
});
Thx Saravenan N, i've found the answer. Declare imageso after the document ready function
$(function(){
var imageso;
// Prepare the preview for profile picture
$("#profile_image").change(function(){
$("#message").empty(); // To remove the previous error message
var file = this.files[0];
var imagefile = file.type;
var match= ["image/jpeg","image/png","image/jpg"];
if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2])))
{
$('#wizardPicturePreview1').attr('src','/images/houses/default.png');
$("#message").html("<p id='error'>Please Select A valid Image File</p>"+"<h4>Note</h4>"+"<span id='error_message'>Only jpeg, jpg and png Images type allowed</span>");
return false;
}
else
{
var reader = new FileReader();
reader.onload = function (e) {
$('#wizardPicturePreview1').attr('src', e.target.result).fadeIn('slow');
//getting the base64 string of the uploaded image
imageso = e.target.result;
console.log('Encoded image:', imageso);
};
reader.readAsDataURL(this.files[0]);
}
});
$('form').submit(function() {
// submit the encoded base64 string of the uploaded image
$('.hidden-image-data').val(imageso);
var formValue = $(this).serialize();
$('#result-data').text(formValue);
// Prevent the form from actually submitting
return true;
});
});
I am trying to make it so that a user can upload an image and get the image encoded and saved into database and server. I do not have any experience with base64. I have the rest of my inputs saving, just cant figure out how to save image. my html code is
<input id="inputFileToLoad" type="file" onchange="encodeImageFileAsURL();"
accept="image/gif, image/jpeg, image/png" />
<div id="imgTest"></div>
my javascript is as follows and i ge an error thatt prompts encodeImageFileAsURL() is not defined.
function encodeImageFileAsURL() {
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
var srcData = fileLoadedEvent.target.result; // <--- data: base64
var newImage = document.createElement('img');
newImage.src = srcData;
document.getElementById("imgTest").innerHTML = newImage.outerHTML;
alert("Converted Base64 version is " +
document.getElementById("imgTest").innerHTML);
console.log("Converted Base64 version is " +
document.getElementById("imgTest").innerHTML);
}
fileReader.readAsDataURL(fileToLoad);
}
}
all help is appreciated thank you.
I have an audio Link:
var au='https://firebasestorage.googleapis.com/v0/b/test-46a7f.appspot.com/o/Audio.mp3?alt=media&token=a4fa9b18-ab70-4bbc-8ae1-21639d411035';
I need to convert the audio to base64, because its play on mobile devices with a very big delay.
Please see working plunkr https://plnkr.co/edit/PFfebmnqH0eQR9I92v0G?p=preview, Its in Angular 2
Core Logic is JS method :
HTML
<input type="file" id="filePicker" (change)="handleFileSelect($event)">
JavaScript:
handleFileSelect(evt){
var files = evt.target.files;
var file = files[0];
if (files && file) {
var reader = new FileReader();
reader.onload =this._handleReaderLoaded.bind(this);
reader.readAsBinaryString(file);
}
}
_handleReaderLoaded(readerEvt) {
var binaryString = readerEvt.target.result;
this.base64textString= btoa(binaryString);
console.log(btoa(binaryString));
}
If have an input type file
<input id="file" type="file" name="file" />
and an Image
<img id="img">
If a file is selected I want to read Exif data from the image an load it into the img tag.
var $inputFile = $("#file");
$inputFile.on("change", function() {
var img = document.getElementById("img");
var files = $inputFile[0].files;
var reader = new FileReader()
reader.onload = function(event) {
var file = reader.result;
// this is not working
img.src = file;
var binaryString = reader.result;
var oFile = new BinaryFile(binaryString, 0, file.size);
var exif = EXIF.readFromBinaryFile(oFile);
// read exif data
}
reader.readAsBinaryString(files[0]);
});
The problem is that I did not get any image on the screen. It only shows up if I use reader.readAsDataURL(files[0]); but this I cannot use because I need the binaryString for the Exif data.
How do I get the image tag to show the selected file which is a binary string?
to show an image in "binary" form, you need to have it as a base62 encoded string, aka "dataURL".
To use it binary and put it as the src you can make a ObjectURL.
var objectURL = URL.createObjectURL(blob);
image.src=objectURL;
You don't need a fileReader for this, but you will need fileReader for your exif analysis