I'm new to this asynchrony and I'm going crazy. When I finish this, I will try to find out more about it.
My question is, I need to validate on the client side a form. I would like to verify the file if it is really an image, since we can change the extension and pass it by image. I am using this code but of course, the checkFileType function is asynchronous.
In short: I want the file to be validated if it is an image (png, gif or jpg extensions), if it is really an image that displays the image in a preview and / or shows an error.
The code I have is that may be unfinished but it is the following
$('input[type=file]#imagencabecera').change(function(){
var file = (this.files[0].name).toString();
var type = (this.files[0].type).toString();
var reader = new FileReader();
console.log(type);
$('#file-info').text('');
$('#file-info').text(file);
reader.onload = function (e){
$('#filepreview img').attr('src', e.target.result);
}
reader.readAsDataURL(this.files[0]);
});
function checkFileType(file){
if (window.FileReader && window.Blob)
// All the File APIs are supported. Si soporta HTML5 FileReader y Blob
{
var slice = file.slice(0,4); // Get the first 4 bytes of a file
var reader = new FileReader(); // Create instance of file reader. It is asynchronous!
reader.readAsArrayBuffer(slice); // Read the chunk file and return to blob
reader.onload = function(e) {
var buffer = reader.result; // The result ArrayBuffer
var view = new DataView(buffer); // Get access to the result bytes
var signature = view.getUint32(0, false).toString(16); // Read 4 bytes, big-endian,return hex string
switch(signature) // Every file has a unique signature, we can collect them and create a data lib
{
case "89504e47": file.verified_type = "image/png"; break;
case "47494638": file.verified_type = "image/gif"; break;
case "FFd8FFe0": file.verified_type = "image/jpeg"; break;
case "FFd8FFe1": file.verified_type = "image/jpeg"; break;
case "FFd8FFe2": file.verified_type = "image/jpeg"; break;
case "FFd8FFe3": file.verified_type = "image/jpeg"; break;
case "FFd8FFe8": file.verified_type = "image/jpeg"; break;
default: file.verified_type = 0;
}
}
}
else
// File and Blob are not supported
{
}
}
Thank you for your attention