Based on my previous post How can I convert an image into Base64 string from an image source? i would like to set my image file to have a size limit but however i couldnt get it to work if i set with a condition?
here the code below
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("output").src = newImage.src;
alert("Converted Base64 version is " + document.getElementById("output").src);
console.log("Converted Base64 version is " + document.getElementById("output").src);
}
fileReader.readAsDataURL(fileToLoad);
}
}
var uploadField = document.getElementById("inputFileToLoad");
uploadField.onchange = function() {
// 1000000 = 1MB
if (this.files[0].size > 1000000) {
alert("File is too big!");
this.value = "";
} else if (this.files[0].size < 100000) {
alert("File not recommended size!");
this.value = "";
}
};
$('#inputFileToLoad').change(function(event) {
if(event.target.files[0]){
// var tmppath = URL.createObjectURL(event.target.files[0]);
$("img#output").fadeIn("fast").attr('src',URL.createObjectURL(event.target.files[0]));
}else{
alert('Image size mismatched.')
}
// $("#disp_tmp_path").html("Temporary Path(Copy it and try pasting it in browser address bar) --> <strong>["+tmppath+"]</strong>");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="inputFileToLoad" type="file" onchange="encodeImageFileAsURL();" />
<img src="https://mdbootstrap.com/img/Photos/Others/placeholder-avatar.jpg" id="output" width="100" height="100" style="border-radius: 50%;" />
If i have my condition my data of base 64 dont show anymore how can i fix this issue ?