Validare l'estensione dei file per l'upload è un compito che jQuery svolge agevolmente. Vediamo insieme i dettagli di questa soluzione.
Dobbiamo semplicemente estrarre l'estensione del file dal campo di input e confrontarla con una white list di estensioni ammesse. Per esempio, dato il seguente form che accetta solo file JPEG:
<form action="#" method="post" enctype="multipart/form-data">
<div>
<label for="image">Upload image (JPEG only)</label>
<input type="file" name="image" id="image">
</div>
</form>
possiamo definire il seguente plugin:
(function($) {
$.fn.checkFileType = function( options ) {
var defaults = {
allowedExtensions: [],
success: function() {},
error: function() {}
};
options = $.extend( defaults, options );
return this.each(function() {
$( this ).on( "change", function() {
var value = $( this ).val(),
file = value.toLowerCase(),
extension = file.substring( file.lastIndexOf( "." ) + 1 );
if ( $.inArray( extension, options.allowedExtensions ) == -1 ) {
options.error();
$( this ).focus();
} else {
options.success();
}
});
});
};
})(jQuery);
Nel nostro caso le estensioni saranno jpg
e jpeg
:
$(function() {
$( "#image" ).checkFileType({
allowedExtensions: [ "jpg", "jpeg" ],
success: function() {
//
},
error: function() {
//
}
});
});