kamal rumba kamal rumba - 4 months ago 45
jQuery Question

check file type in dropzone

I have following code to upload excel sheet using dropzonejs with certain condition such as maximum number of file is 1 and only excel type is accepted...
when multiple file is uploaded wiht correct file type then the error is initiated first and message is generated by

alert('please enter correct file format')
and then only the real error message is alerted by
alert('You cannot upload more then 1 file at a time.')
. so, my question is how to show real error message when error is initialized...

<script>
var myDropzone = new Dropzone("div#myAwesomeDropzone",
{ url: "<?php echo base_url(); ?>test/upload_excel_file",maxFiles: 1,
acceptedFiles: ".xls,.xlsx",dictDefaultMessage: 'Drag an excel sheet here
to upload, or click to select one',
init : function(){this.on("maxfilesexceeded",function(file)
{
alert('You cannot upload more then 1 file at a time.');
this.removeFile(file);
});

this.on("error",function(file)
{
var type = file.type;
//alert(type);
if(type != 'application/vnd.ms-excel')
{
alert('please enter correct file format');
this.removeFile(file);
}
else if(type != 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
{
alert('please enter correct file format');
this.removeFile(file);
}
});
}
});
</script>

Answer

The incorrect file type message happens because you with your if statements you will obviously fall into one of the 2 conditions giving the error.

So instead you should use:

switch(file.type)
{
    case 'application/vnd.ms-excel':
    case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
    break;
    default:
    alert('please enter correct file format');
    break;
}