Condition of filesize cause base 64 string to be gone? - javascript

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 ?

The code in the question has three separate event handlers for onchange of #inputFileToLoad. There is one declared on the element in the HTML which calls encodeImageFileAsURL(). This is then overwritten on line 25 with uploadField.onchange = function() { preventing encodeImageFileAsURL() from being called. A further onchange handler is then added on line 36 with $('#inputFileToLoad').change(function(event) {.
You could place all of this logic in a single event handler for onchange. This allows you to order the logic as you wish, also you can return if there is an issue (e.g. file size too large) preventing the remaining code from executing.
In the example below I have:
Added the event to be passed as a parameter to encodeImageFileAsURL(event) in the HTML onchange="encodeImageFileAsURL(event);
Moved the code from the various event handlers into the encodeImageFileAsURL function, changing references of this to event.target.
Added some return statements if the file size checks fail to prevent the remaining code from executing
Example is below,
function encodeImageFileAsURL(event) {
// File Size Checks
if (event.target.files[0].size > 1000000) {
alert("File is too big!");
event.target.value = "";
return;
} else if (event.target.files[0].size < 100000) {
alert("File not recommended size!");
event.target.value = "";
return;
}
// Update image on page
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.')
return;
}
// Base64 conversion
var filesSelected = event.target.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);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="inputFileToLoad" type="file" onchange="encodeImageFileAsURL(event);" />
<img src="https://mdbootstrap.com/img/Photos/Others/placeholder-avatar.jpg" id="output" width="100" height="100" style="border-radius: 50%;" />

Related

How to get XML file content in React? [duplicate]

I want to show contents of uploaded file in html, I can just upload a text file.
My example.html:
<html xmlns="http://www.w3.org/1999/xhtml" >
<p>
Please specify a file, or a set of files:<br>
<input type="file" name="datafile" size="40">
</p>
<textarea id="2" name="y" style="width:400px;height:150px;"></textarea>
</html>
How can I show contents of any uploaded text file in textarea shown below?
I've came here from google and was surprised to see no working example.
You can read files with FileReader API with good cross-browser support.
const reader = new FileReader()
reader.onload = event => console.log(event.target.result) // desired file content
reader.onerror = error => reject(error)
reader.readAsText(file) // you could also read images and other binaries
See fully working example below.
document.getElementById('input-file')
.addEventListener('change', getFile)
function getFile(event) {
const input = event.target
if ('files' in input && input.files.length > 0) {
placeFileContent(
document.getElementById('content-target'),
input.files[0])
}
}
function placeFileContent(target, file) {
readFileContent(file).then(content => {
target.value = content
}).catch(error => console.log(error))
}
function readFileContent(file) {
const reader = new FileReader()
return new Promise((resolve, reject) => {
reader.onload = event => resolve(event.target.result)
reader.onerror = error => reject(error)
reader.readAsText(file)
})
}
label {
cursor: pointer;
}
textarea {
width: 400px;
height: 150px;
}
<div>
<label for="input-file">Specify a file:</label><br>
<input type="file" id="input-file">
</div>
<textarea id="content-target"></textarea>
Here's one way:
HTML
<tr>
<td>Select a File to Load:</td>
<td><input type="file" id="fileToLoad"></td>
<td><button onclick="loadFileAsText()">Load Selected File</button><td>
</tr>
JavaScript
function loadFileAsText(){
var fileToLoad = document.getElementById("fileToLoad").files[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent){
var textFromFileLoaded = fileLoadedEvent.target.result;
document.getElementById("inputTextToSave").value = textFromFileLoaded;
};
fileReader.readAsText(fileToLoad, "UTF-8");
}
Try this.
HTML
<p>
Please specify a file, or a set of files:<br>
<input type="file" id="myFile" multiple size="50" onchange="myFunction()">
</p>
<textarea id="demo" style="width:400px;height:150px;"></textarea>
JS
function myFunction(){
var x = document.getElementById("myFile");
var txt = "";
if ('files' in x) {
if (x.files.length == 0) {
txt = "Select one or more files.";
} else {
for (var i = 0; i < x.files.length; i++) {
txt += (i+1) + ". file";
var file = x.files[i];
if ('name' in file) {
txt += "name: " + file.name + "";
}
if ('size' in file) {
txt += "size: " + file.size + " bytes ";
}
}
}
}
else {
if (x.value == "") {
txt += "Select one or more files.";
} else {
txt += "The files property is not supported by your browser!";
txt += "The path of the selected file: " + x.value; // If the browser does not support the files property, it will return the path of the selected file instead.
}
}
document.getElementById("demo").innerHTML = txt;
}
Demo

JavaScript, csv to json, split is not a function [duplicate]

I want to show contents of uploaded file in html, I can just upload a text file.
My example.html:
<html xmlns="http://www.w3.org/1999/xhtml" >
<p>
Please specify a file, or a set of files:<br>
<input type="file" name="datafile" size="40">
</p>
<textarea id="2" name="y" style="width:400px;height:150px;"></textarea>
</html>
How can I show contents of any uploaded text file in textarea shown below?
I've came here from google and was surprised to see no working example.
You can read files with FileReader API with good cross-browser support.
const reader = new FileReader()
reader.onload = event => console.log(event.target.result) // desired file content
reader.onerror = error => reject(error)
reader.readAsText(file) // you could also read images and other binaries
See fully working example below.
document.getElementById('input-file')
.addEventListener('change', getFile)
function getFile(event) {
const input = event.target
if ('files' in input && input.files.length > 0) {
placeFileContent(
document.getElementById('content-target'),
input.files[0])
}
}
function placeFileContent(target, file) {
readFileContent(file).then(content => {
target.value = content
}).catch(error => console.log(error))
}
function readFileContent(file) {
const reader = new FileReader()
return new Promise((resolve, reject) => {
reader.onload = event => resolve(event.target.result)
reader.onerror = error => reject(error)
reader.readAsText(file)
})
}
label {
cursor: pointer;
}
textarea {
width: 400px;
height: 150px;
}
<div>
<label for="input-file">Specify a file:</label><br>
<input type="file" id="input-file">
</div>
<textarea id="content-target"></textarea>
Here's one way:
HTML
<tr>
<td>Select a File to Load:</td>
<td><input type="file" id="fileToLoad"></td>
<td><button onclick="loadFileAsText()">Load Selected File</button><td>
</tr>
JavaScript
function loadFileAsText(){
var fileToLoad = document.getElementById("fileToLoad").files[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent){
var textFromFileLoaded = fileLoadedEvent.target.result;
document.getElementById("inputTextToSave").value = textFromFileLoaded;
};
fileReader.readAsText(fileToLoad, "UTF-8");
}
Try this.
HTML
<p>
Please specify a file, or a set of files:<br>
<input type="file" id="myFile" multiple size="50" onchange="myFunction()">
</p>
<textarea id="demo" style="width:400px;height:150px;"></textarea>
JS
function myFunction(){
var x = document.getElementById("myFile");
var txt = "";
if ('files' in x) {
if (x.files.length == 0) {
txt = "Select one or more files.";
} else {
for (var i = 0; i < x.files.length; i++) {
txt += (i+1) + ". file";
var file = x.files[i];
if ('name' in file) {
txt += "name: " + file.name + "";
}
if ('size' in file) {
txt += "size: " + file.size + " bytes ";
}
}
}
}
else {
if (x.value == "") {
txt += "Select one or more files.";
} else {
txt += "The files property is not supported by your browser!";
txt += "The path of the selected file: " + x.value; // If the browser does not support the files property, it will return the path of the selected file instead.
}
}
document.getElementById("demo").innerHTML = txt;
}
Demo

Conditional alerts based on file type upload

Hi all and thanks for your patient because:
first, this is my first question so let me know in i make any mistake.
second, i'm a javascript/jquery noob.
I wrote a javascript code that checks for image upload and runs various alerts based on the check's result.
The script must validate both file types (image and pdf). But for images it must validate size and dimensions. For pdf it must validate size only.
Something like "if is image then check width height and size" "if not an image but it's a pdf then check file size" and "if is not an image and if is not a pdf then retur file type error"
Now I would like to allow pdf on upload and check its size and then return an alert.
But I really don't know how to distinguish different file types programmaticaly.
Here's my original code:
jQuery( document ).ready(function($) {
var _URL = window.URL || window.webkitURL;
var submits = document.getElementsByClassName('gform_button');
var submit = submits[0];
$(".customUpload input:file").click(function(e) {
this.value = "";
submit.disabled = false;
});
$(".customUpload input:file").change(function(e) {
var file, img;
var width, height, size, sizeInMB;
if ((file = this.files[0])) {
img = new Image();
img.onload = function() {
width = this.width;
height = this.height;
size = this.size;
sizeInMB = (size / (1024*1024)).toFixed(2);
if (sizeInMB > 20) {
alert("File is to big");
submit.disabled = true;
}
if (width < 300 || height < 300) {
alert("Image size is lower than 300px");
submit.disabled = true;
};
};
img.onerror = function() {
alert( "not a valid file: " + file.type);
submit.disabled = true;
};
img.src = _URL.createObjectURL(file);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="customUpload">
<form action="" class="cart">
<input type="file" id="file" /> <!-- accept="image/gif, image/jpeg, image/png, image/tiff" -->
<button type="submit" id ="submit" name="submit" class="single_add_to_cart_button gform_button">SUBMIT</button>
</form>
</div>
Many thanks to all and have a good day.
I added this code to get the extension (with the dot) and the size
var fileExtension = file.name.substr(file.name.length - 4, 4);
var fileSize = file.size;
jQuery( document ).ready(function($) {
var _URL = window.URL || window.webkitURL;
var submits = document.getElementsByClassName('gform_button');
var submit = submits[0];
$(".customUpload input:file").click(function(e) {
this.value = "";
submit.disabled = false;
});
$(".customUpload input:file").change(function(e) {
var file, img;
var width, height, size, sizeInMB;
if ((file = this.files[0])) {
var fileExtension = file.name.substr(file.name.length - 4, 4);
var fileSize = file.size;
alert(fileExtension + " file with size of " + fileSize);
img = new Image();
img.onload = function() {
width = this.width;
height = this.height;
size = file.size;
sizeInMB = (size / (1024*1024)).toFixed(2);
if (sizeInMB > 20) {
alert("File is to big");
submit.disabled = true;
}
if (width < 300 || height < 300) {
alert("Image size is lower than 300px");
submit.disabled = true;
};
};
img.onerror = function() {
alert( "not a valid file: " + file.type);
submit.disabled = true;
};
img.src = _URL.createObjectURL(file);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="customUpload">
<form action="" class="cart">
<input type="file" id="file" /> <!-- accept="image/gif, image/jpeg, image/png, image/tiff" -->
<button type="submit" id ="submit" name="submit" class="single_add_to_cart_button gform_button">SUBMIT</button>
</form>
</div>

Reading uploaded text file contents in html

I want to show contents of uploaded file in html, I can just upload a text file.
My example.html:
<html xmlns="http://www.w3.org/1999/xhtml" >
<p>
Please specify a file, or a set of files:<br>
<input type="file" name="datafile" size="40">
</p>
<textarea id="2" name="y" style="width:400px;height:150px;"></textarea>
</html>
How can I show contents of any uploaded text file in textarea shown below?
I've came here from google and was surprised to see no working example.
You can read files with FileReader API with good cross-browser support.
const reader = new FileReader()
reader.onload = event => console.log(event.target.result) // desired file content
reader.onerror = error => reject(error)
reader.readAsText(file) // you could also read images and other binaries
See fully working example below.
document.getElementById('input-file')
.addEventListener('change', getFile)
function getFile(event) {
const input = event.target
if ('files' in input && input.files.length > 0) {
placeFileContent(
document.getElementById('content-target'),
input.files[0])
}
}
function placeFileContent(target, file) {
readFileContent(file).then(content => {
target.value = content
}).catch(error => console.log(error))
}
function readFileContent(file) {
const reader = new FileReader()
return new Promise((resolve, reject) => {
reader.onload = event => resolve(event.target.result)
reader.onerror = error => reject(error)
reader.readAsText(file)
})
}
label {
cursor: pointer;
}
textarea {
width: 400px;
height: 150px;
}
<div>
<label for="input-file">Specify a file:</label><br>
<input type="file" id="input-file">
</div>
<textarea id="content-target"></textarea>
Here's one way:
HTML
<tr>
<td>Select a File to Load:</td>
<td><input type="file" id="fileToLoad"></td>
<td><button onclick="loadFileAsText()">Load Selected File</button><td>
</tr>
JavaScript
function loadFileAsText(){
var fileToLoad = document.getElementById("fileToLoad").files[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent){
var textFromFileLoaded = fileLoadedEvent.target.result;
document.getElementById("inputTextToSave").value = textFromFileLoaded;
};
fileReader.readAsText(fileToLoad, "UTF-8");
}
Try this.
HTML
<p>
Please specify a file, or a set of files:<br>
<input type="file" id="myFile" multiple size="50" onchange="myFunction()">
</p>
<textarea id="demo" style="width:400px;height:150px;"></textarea>
JS
function myFunction(){
var x = document.getElementById("myFile");
var txt = "";
if ('files' in x) {
if (x.files.length == 0) {
txt = "Select one or more files.";
} else {
for (var i = 0; i < x.files.length; i++) {
txt += (i+1) + ". file";
var file = x.files[i];
if ('name' in file) {
txt += "name: " + file.name + "";
}
if ('size' in file) {
txt += "size: " + file.size + " bytes ";
}
}
}
}
else {
if (x.value == "") {
txt += "Select one or more files.";
} else {
txt += "The files property is not supported by your browser!";
txt += "The path of the selected file: " + x.value; // If the browser does not support the files property, it will return the path of the selected file instead.
}
}
document.getElementById("demo").innerHTML = txt;
}
Demo

trying to leverage JSZip to open and then parse a specific file in a .zip

Have been trying to use the JSZip library to cycle through files in a .zip, looking for one (here, test.txt) that I want to parse for content.
Have attempted to do a modification of the sample [recommend viewing source on that] that JSZip provides:
<!DOCTYPE HTML>
<html>
<head>
<link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
<link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
</head>
<body>
<div class = "container">
<div class = "hero-unit">
<input type="file" class="span7" id="input" name="file" multiple /> <!-- redo this in a bootstrappy way-->
<br>
<output id="output"></output>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="/js/jszip-load.js"></script>
<script src="/js/jszip.js"></script>
<script src="/js/jszip-inflate.js"></script>
<script>
if (window.File && window.FileReader && window.FileList && window.Blob) {
// Great success! All the File APIs are supported.
} else {
alert('The File APIs are not fully supported in this browser.');
}
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// files is a FileList of File objects. List some properties.
var output = [];
for (var i = 0, f; f = files[i]; i++) {
if (f.type !== "application/zip") {
document.getElementById('output').innerHTML = "<p class='text-error'>" + f.name + " isn't a zip file.</div>";
continue;
}
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
var zip = new JSZip(e.target.result)
$.each(zip.files, function (index, zipEntry) {
if (zipEntry.name == "test.txt"){
var text = zipEntry.asText();
var lines = text.split(/[\r\n]+/g); // tolerate both Windows and Unix linebreaks
for(var i = 0; i < lines.length; i++) {
if (lines[i].length > 240){
output.push('<li>' + lines[i] + '<br>');
}
}
document.getElementById('output').innerHTML = '<h2>Paths with more than 240 characters:</h2> <br><ol>' + output.join('') + '</ol>';
else{
alert("file not found!")
}
}
});
}
})(f);
}
}
document.getElementById('input').addEventListener('change', handleFileSelect, false);
</script>
</body>
</html>
For some reason, I'm sure having to do with the way that I am using the closure, it is not actually parsing the .zip files in question. Any ideas what I might be doing wrong here?
I use this code and am able to get all file data. content variable has file content:
function loadSettingsFile(evt) {
var files = evt.target.files;
for (var i = 0, f; f = files[i]; i++) {
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
try {
var zip = new JSZip(e.target.result);
$.each(zip.files, function (index, zipEntry) {
var content = zipEntry.asText();
alert(content);
});
} catch(e) {
alert(e)
}
}
})(f);
// read the file !
// readAsArrayBuffer and readAsBinaryString both produce valid content for JSZip.
reader.readAsArrayBuffer(f);
// reader.readAsBinaryString(f);
}
}

Categories

Resources