Skip to content
Advertisement

check file type in dropzone

I have following code to upload excel sheet using dropzone.js with certain condition such as maximum number of file is 1 and only excel type is accepted… when multiple file is uploaded with 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…

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);
      }
    });
  },
});

Advertisement

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;
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement