Reputation: 2654
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" />
Upvotes: 2
Views: 2199
Reputation: 156572
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);
Upvotes: 5