How to submit base64 string of an uploaded image using only jquery - javascript

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;
});
});

Related

Is there a way to pull data from a txt file and make it update everytime the txt file is updated?

Is there a way to pull data from a txt file and make it update everytime the txt file is updated? I'm using the following code in my program and it will find the file and display its content fine but when I update the txt file, the program does not update the new text.
function OnFileLoad()
{
var file = document.getElementById("FileReader").files[0];
var fileDisplayArea = document.getElementById("FileContent");
if (file.type.match('text.*|image.*|application.*'))
{
console.log('hello. we are inside the function')
var reader = new FileReader();
reader.onload = function (e)
{
fileDisplayArea.innerText = reader.result;
}
reader.readAsText(file);
}
else
{
fileDisplayArea.innerText = "File not supported!"
}
}

How to convert input file .pdf in string Base64?

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>

Reading uploaded text file contents in variable

I want to read string from text file and save it in variable . What I did:
HTML:
<div>
Select a text file:
<input type="file" id="fileInput">
</div>
<pre id="fileDisplayArea"><pre>
JS:
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
var newString;
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
fileDisplayArea.innerText = reader.result;
}
newString=reader.result; //SAVE RESULT
alert(newString);
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!"
}
});
}
I want to save text from file and alert it. But it doesnt work.
I did it:
var tfile;
var reader = new FileReader();
function rdfile(files)
{
tfile = files[0];
reader.readAsText(tfile, 'CP1251');
reader.onload = function(e)
{
str = e.target.result;
alert(str);
};
}
But it doesnt work too. I alert many different symbols but not my text.
Look at your code from your first attempt:
newString=reader.result; //SAVE RESULT
alert(newString);
reader.readAsText(file);
Get the result
Alert it
Do the thing that generates the result
You have to read the file before you can look at the text you get from reading it!
Move steps 1 and 2 in to the onload event handler you already have.
Now look at your second attempt. You never call rdfile and you never call readAsText.

jQuery Validate File Type On Change

I have a jQuery File Upload. That upload function is only allow image type. .jpg, .gif, .png
Assume I have 2 file, that's a.jpg & b.pdf. Now, I change the extension b.pdf to be b.jpg
a.jpg is original image.
b.jpg is not an original image.
My question, how can I validate that b.jpg is not an original image?
Here is my JS script :
$(function()
{
$("#file").change(function()
{
var file = this.files[0];
var imagefile = file.type;
var match= ["image/jpeg","image/png","image/jpg"];
var file_size = this.files[0].size;
if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2])))
{
alert("Invalid File");
}
else
{
var reader = new FileReader();
reader.onload = imageIsLoadeds;
reader.readAsDataURL(this.files[0]);
}
function imageIsLoadeds(e)
{
if(file_size>=1024000)
{
alert("File Size Error");
}
else
{
$('#image').attr('src', e.target.result);
}
}
}
}
You have to validate the MIME Type of the content being uploaded.
First select the required MIME type (Reference: http://www.freeformatter.com/mime-types-list.html).
Second you can use jQuery Validation Plugin to verify the MIME type of the uploaded content. (Reference: http://jqueryvalidation.org/accept-method/)

How to get base64 from input file in IE without using FileReader or HTML5

I hope I can have help from you. I need to get a file from an HTML input file element.
This is the HTML:
<input type="file" name="allegatoImg" id="allegatoImg" onchange="javascript:readURL(this)"/>
And this is JavaScript:
function readURL(input) {
var mimeType;
if (window.FileReader) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
var dataURL = e.target.result;
mimeType = dataURL.split(",")[0].split(":")[1].split(";")[0];
if (mimeType == 'image/jpeg') {
jQuery('#imgallegato').attr('src', e.target.result);
//jQuery('#fotoTemp').attr('src', e.target.result);
provaInvioImgSrcToServer();
} else {
alert('Errore nella lettura del file. Controllare che sia stato caricato un file con estensione jpeg.');
return;
}
};
reader.readAsDataURL(input.files[0]);
}
} else {
f = document.dettRichAbbForm;
document.getElementById("imgallegato").src = "file:///" + input.value;
var estensione = ctrlExtensionFileIE(input.value);
alert('path file = ' + jQuery("#imgallegato").attr('src') );
if (estensione=='jpg' || estensione=='jpeg') {
provaInvioImgSrcToServer();
} else {
alert('Error in reading file');
return;
}
}
}
function provaInvioImgSrcToServer() {
var urlToCall = provaInvioImgSrcToServerUrl;
alert('img path = ' + jQuery("#imgallegato").attr('src'));
jQuery.ajax({
cache : false,
type : "POST",
timeout : 5000,
url : urlToCall,
data : {imgSource: jQuery("#imgallegato").attr('src')},
success : function(result) {
ritagliaImg();
},
error : function(errorMsg) {
//gestAjaxCallError(errorMsg, divResultBodId, divResultBodId);
alert('Errore nel caricamento dell\'immagine selezionata.');
}
});
}
function ctrlExtensionFileIE(value) {
var splittedVal = value.split(".");
return splittedVal[1];
}
I'm working on Liferay 5.1 with an old version of jQuery so I can't use HTML5 with canvas element, because I should load the image from the input file into a Jcrop element.
My problem is linked to this part of the code:
f = document.dettRichAbbForm;
document.getElementById("imgallegato").src = "file:///" + input.value;
FileReader works fine in Mozilla, Chrome and IE10+, but with IE9- I should use the code above.
The problem is that input.value returns the path of the selected file and I need to get the base64 in order to send it to the server. I can't do the submit of my form, because this approach needs to re-load my jsp and I have others fields.
Is there someone that could help me to get the byte array from selected file on IE without using canvas element, HTML5 and FileReader library?

Categories

Resources