检查 dropzone 中的文件类型

check file type in dropzone

我有以下代码可以使用 dropzone.js 上传 excel sheet 并满足特定条件,例如最大文件数为 1,并且只接受 excel 类型。 . 当使用正确的文件类型上传多个文件时,首先会启动错误,并且 alert('please enter correct file format') 会生成消息,然后 alert('You cannot upload more then 1 file at a time.') 只会提醒真正的错误消息。所以,我的问题是如何在错误初始化时显示真实的错误消息...

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

不正确的文件类型消息的发生是因为您使用 if 语句显然会落入给出错误的 2 个条件之一。

所以你应该使用:

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