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.
Related
Using a JS snippet I found here I am able to preview images prior to upload, here is that code...
function previewImages() {
var preview = document.querySelector('#preview');
if (this.files) {
[].forEach.call(this.files, readAndPreview);
}
function readAndPreview(file) {
// Make sure `file.name` matches our extensions criteria
if (!/\.(jpe?g|png|gif)$/i.test(file.name)) {
return alert(file.name + " is not an image");
} // else...
var reader = new FileReader();
reader.addEventListener("load", function() {
var image = new Image();
image.height = 85;
image.title = file.name;
image.src = this.result;
preview.appendChild(image);
});
reader.readAsDataURL(file);
}
}
document.querySelector('#file-input').addEventListener("change", previewImages);
<input id="file-input" type="file" multiple>
<div id="preview"></div>
My issue is despite the filenames of the images being uploaded being like 1-black, 2-red, 3-blue etc when they are previewed they are in a random order, the desired output would be to show them in alphabetical order.
I have been looking at images.sort(); // use sort function of javascript. but can't figure out how to use it!
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>
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
I'm trying to get image as Object of javascript on the client side to send it using jQuery
<html>
<body>
<script language="JavaScript">
function checkSize()
{
im = new Image();
im.src = document.Upload.submitfile.value;
if(!im.src)
im.src = document.getElementById('submitfile').value;
alert(im.src);
alert(im.width);
alert(im.height);
alert(im.fileSize);
}
</script>
<form name="Upload" action="#" enctype="multipart/form-data" method="post">
<p>Filename: <input type="file" name="submitfile" id="submitfile" />
<input type="button" value="Send" onClick="checkSize();" />
</form>
</body>
</html>
But in this code only alert(im.src) is displaying src of file but alert(im.width),alert(im.height),alert(im.filesize) are not working properly and alerting 0, 0, undefined respectively. Kindly tell me how I can access image object using javascript?
The reason that im.fileSize is only working in IE is because ".fileSize" is only an IE property. Since you have code that works in IE, I would do a check for the browser and render your current code for IE and try something like this for other browsers.
var imgFile = document.getElementById('submitfile');
if (imgFile.files && imgFile.files[0]) {
var width;
var height;
var fileSize;
var reader = new FileReader();
reader.onload = function(event) {
var dataUri = event.target.result,
img = document.createElement("img");
img.src = dataUri;
width = img.width;
height = img.height;
fileSize = imgFile.files[0].size;
alert(width);
alert(height);
alert(fileSize);
};
reader.onerror = function(event) {
console.error("File could not be read! Code " + event.target.error.code);
};
reader.readAsDataURL(imgFile.files[0]);
}
I haven't tested this code but it should work as long as I don't have some typo. For a better understanding of what I am doing here check out this link.
This is what I use and it works great for me. I save the image as a blob in mysql. When clicked, the file upload dialog appears, that is why i set the file input visibility to hidden and set its type to upload image files. Once the image is selected, it replaces the existing one, then I use the jquery post method to update the image in the database.
<div>
<div><img id="logo" class="img-polaroid" alt="Logo" src="' . $row['logo'] . '" title="Click to change the logo" width="128">
<input style="visibility:hidden;" id="logoupload" type="file" accept="image/* ">
</div>
$('img#logo').click(function(){
$('#logoupload').trigger('click');
$('#logoupload').change(function(e){
var reader = new FileReader(),
files = e.dataTransfer ? e.dataTransfer.files : e.target.files,
i = 0;
reader.onload = onFileLoad;
while (files[i]) reader.readAsDataURL(files[i++]);
});
function onFileLoad(e) {
var data = e.target.result;
$('img#logo').attr("src",data);
//Upload the image to the database
//Save data on keydown
$.post('test.php',{data:$('img#logo').attr("src")},function(){
});
}
});
$('#imagess').change(function(){
var total_images=$('#total_images').val();
var candidateimage=document.getElementById('imagess').value;
formdata = false;
var demo=document.getElementById("imagess").files;
if (window.FormData) {
formdata = new FormData();
}
var i = 0, len = demo.length, img, reader, file;
for ( ; i < len; i++ ) {
file = demo[i];
if (file.type.match(/image.*/)) {
if (formdata) {
formdata.append("images", file);
}
}
}
$('#preview').html('Uploading...');
var url=SITEURL+"users/image_upload/"+total_images;
$.ajax({
url: url,
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
$('#preview').html('');
if (res == "maxlimit") {
alert("You can't upload more than 4 images");
}
else if (res == "error") {
alert("Image can't upload please try again.")
}
else {
$('#user_images').append(res);
}
}
});
});