check for ascii plain text - javascript

How can I check if the uploaded file is ascii plain text?
$("#my_file").change(function(){
//alert if not ascii
});
<input type="file" name="my_file" id="my_file" />

Using the HTML5 file APIs (which are not yet finalized and not supported by all versions of all major browsers) you could read the raw file contents via FileReader.readAsBinaryString(file) and ensure that each byte (character) has a value in the ASCII character range (0-127).
For example (see working jsFiddle here):
function ensureAsciiFile(evt) {
var file, files=evt.target.files;
for (var i=0; file=files[i]; i++) {
var reader = new FileReader();
reader.onload = (function(theFile, theReader) {
return function(e) {
var fileContents = theReader.result;
if (fileContents.match(/[^\u0000-\u007f]/)) {
alert('ERROR: non-ASCII file "' + theFile.name + '"');
} else {
alert('OK: ASCII file "' + theFile.name + '"');
}
};
})(file, reader);
reader.readAsBinaryString(file);
}
}
$('#my_file').change(ensureAsciiFile);

Related

How to get multiple files base64 and each filenames via FileReaderAPI in Javascript?

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;">

AngularJS: Is there any way to get size of file?

I'm implementing a check in which I dont want to upload the image which has size greater than 4MB. I'm using file reader and new image(). I've the image size and width. But how can I get the filesize.
function previewImage(element) {
var reader = new FileReader();
reader.onload = function (event) {
seAddArtist.imageSource = event.target.result;
$scope.$apply();
};
// when the file is read it triggers the onload event above.
reader.readAsDataURL(element.files[0]);
}
var img = new Image();
img.onload = function () {
alert(this.width + 'x' + this.height);
}
I am implementing these two combine but how can i check the size of image?
FileReader (FileReader API) itself does not provide the size of an file. You need to use file (file API) instead:
function previewImage(element) {
var reader = new FileReader();
reader.onload = function(event) {
seAddArtist.imageSource = event.target.result;
$scope.$apply();
};
// when the file is read it triggers the onload event above.
reader.readAsDataURL(element.files[0]);
//log / access file size in bytes
console.log(element.files[0].size + ' Bytes');
//log / access file size in Mb
console.log(element.files[0].size/1024/1024 + ' MB');
if (element.files[0].size/1024/1024 > 4) {
console.log('file is bigger than 4MB);
}
}
That might be what you want:
var size = files[0].size;
You can check the file size before submitting:
<!doctype HTML>
<html>
<head>
<script>
function checkFileSize() {
var size = document.getElementById("fileSelector").files[0].size;
alert("file size: " + size);
}
</script>
</head>
<body>
<input id="fileSelector" type="file" onchange="checkFileSize()"/>
<input type="submit" />
</body>
</html>
This is working code to get file size. you will get file size in KB.
<input id="file" type="file">
<img id="filerendered" src="">
and in script tag
document.getElementById('file').onchange = function (event) {
var targetn = event.target || window.event.srcElement,
files = targetn.files;
// FileReader here
if (FileReader && files && files.length) {
var thisReader = new FileReader();
alert("your file size "+ (files[0].size)/1024 + "kb")
thisReader.onload = function () {
document.getElementById("filerendered").src = thisReader.result;
}
thisReader.readAsDataURL(files[0]);
}
// for Not supported case
else {
// not supported
}
}

How to preserve old files after new file browse click in multiple file uploader?

I've made a file upload with file previews using html5+file reader and it works fine except that old files the user selected gets destroyed from input file field and if the user select in a new single browse click.
Here's the js fiddle
https://jsfiddle.net/sco3pq3b/
html
<p> UPLOAD </p>
<input type="file" multiple="yes" name="photo[]" id="photos">
<div id="preview"></div>
js
$("#photos").change(function(){
var fileList = this.files;
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
for(var i = 0; i < fileList.length; i++){
if (regex.test(fileList[0].name.toLowerCase())) {
var reader = new FileReader();
reader.onload = function (e) {
$('#preview').append('<div class="imgLinkWrap"><a class="fancybox" href="' + e.target.result +'">'+fileList[0].name.toLowerCase()+'</a></div>');
}
console.log(fileList[i]);
reader.readAsDataURL(fileList[i]);
} else {
alert(file[0].name + " is not a valid image file.");
$('#preview').html("");
return false;
}
}
});
Is there anyway to preserve the old files after a new browse file click without using any plugin or ajax?
You can store the files uploaded in a local array of files that will be preserved. This is how I modified your js and this seems to work fine.
var fileList=[];
$("#photos").change(function(){
fileList.push.apply(fileList,this.files); // appends files objects to local array
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
for(var i = 0; i < fileList.length; i++){
if (regex.test(fileList[0].name.toLowerCase())) {
var reader = new FileReader();
reader.onload = function (e) {
$('#preview').append('<div class="imgLinkWrap"><a class="fancybox" href="' + e.target.result +'">'+fileList[0].name.toLowerCase()+'</a></div>');
}
console.log(fileList[i]);
reader.readAsDataURL(fileList[i]);
} else {
alert(file[0].name + " is not a valid image file.");
$('#preview').html("");
return false;
}
}
});
You want to preserve old files , add them in global variable
var fileList //here
$("#photos").change(function(){
alert(fileList); //use them
fileList = this.files;
alert(fileList);
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
for(var i = 0; i < fileList.length; i++){
if (regex.test(fileList[0].name.toLowerCase())) {
var reader = new FileReader();
reader.onload = function (e) {
$('#preview').append('<div class="imgLinkWrap"><a class="fancybox" href="' + e.target.result +'">'+fileList[0].name.toLowerCase()+'</a></div>');
}
console.log(fileList[i]);
reader.readAsDataURL(fileList[i]);
} else {
alert(file[0].name + " is not a valid image file.");
$('#preview').html("");
return false;
}
}
});
Edit :
As you need them after the form submitting you can use HTML5 Local Storage it stores the data with no expiration date
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
If you want to store the data for only one session. The data is deleted when the user closes the specific browser tab use The sessionStorage Object
more about HTML5 Local Storage and sessionStorage and here :http://www.w3schools.com/html/html5_webstorage.asp

Get all images from local folder

I need a way to get all the images from a local folder for a presentation that will also run locally. There will be no attempt for a server to take the images from a local folder since that is not possible/the case.
I need to use .js since I can't use .php (which would be easier) since it runs on a local PC.
Say I need to take all the images from learn/
I have tried various solutions that can be found here, here and here but none worked.
I think your best option is to use the new File API in Javascript. Is has a lot of functions to read files from the file system.
<input type="file" id="fileinput" multiple />
<script type="text/javascript">
function readMultipleFiles(evt) {
//Retrieve all the files from the FileList object
var files = evt.target.files;
if (files) {
for (var i=0, f; f=files[i]; i++) {
var r = new FileReader();
r.onload = (function(f) {
return function(e) {
var contents = e.target.result;
alert( "Got the file.n"
+"name: " + f.name + "n"
+"type: " + f.type + "n"
+"size: " + f.size + " bytesn"
+ "starts with: " + contents.substr(1, contents.indexOf("n"))
);
};
})(f);
r.readAsText(f);
}
} else {
alert("Failed to load files");
}
}
document.getElementById('fileinput').addEventListener('change', readMultipleFiles, false);
</script>
(code from here)
You can find a good explanation and helpful code here.
Thanks to Patrick Hofman's answer, I modified the code and ended up with this :
$(document).ready(function(){
function readMultipleFiles(evt) {
//Retrieve all the files from the FileList object
var files = evt.target.files;
if (files) {
for (var i=0, f; f=files[i]; i++) {
var r = new FileReader();
r.onload = (function(f) {
return function(e) {
var contents = e.target.result;
$('body').append('<h1>' + f.name + '</h1><img src="learn/' + f.name + '"/>');
};
})(f);
r.readAsText(f);
}
} else {
alert("Failed to load files");
}
}
document.getElementById('fileinput').addEventListener('change', readMultipleFiles, false);
});

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