【问题标题】:Dropzone check if files names exists before processing queueDropzone 在处理队列之前检查文件名是否存在
【发布时间】:2020-07-18 17:38:54
【问题描述】:

我正在使用 dropzone 上传文件,这些文件与后端数据库中的一些元数据一起保存。 当用户尝试上传大量文件时,我想检查他是否已经上传了具有此名称的文件,并通过警报警告他,并选择继续或停止。

所以我禁用了autoProcessQueue。 我也在监听addedfile事件,我得到了名字,我执行了一个ajax来检查它是否存在于数据库中并返回true或false,很好。

假设用户尝试上传 40 个已经存在的文件,我不想要 40 个警告该文件已经存在,我想要一个通知打印所有 40 个文件名。 我一直在寻找 addedfile 但对于多个文件,我没有找到解决方案。

这是我现在的代码 这就是我卡住的地方 我如何知道我何时检查了每个文件?

$(document).ready(function() {
        @if(isset($checkRoute))
            function filenameExists(name) {
                $.ajax({
                    type: 'GET',
                    url: '{{ $checkRoute }}',
                    data: {
                        name: name
                    }
                })
                .done(function(res) {
                    // returns true or false
                    return res
                })
                .fail(function(err) {
                    console.log(err)
                })
            }
        @endif

        let existingFilenames = []

        let fileCount = 0

        $('#{{ $element_id }}').dropzone({
            url: "{{ $upload }}", // Set the url for your upload script location
            paramName: "documents", // The name that will be used to transfer the file
            maxFiles: 100,
            maxFilesize: 100, // MB
            parallelUploads: 100,
            timeout: 240000,
            addRemoveLinks: true,
            acceptedFiles: "application/msword, application/vnd.ms-excel, application/pdf, image/*, application/vnd.openxmlformats-officedocument.wordprocessingml.document, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, image/*",
            uploadMultiple: true,
            headers: {
                'X-CSRF-TOKEN': "{{ csrf_token() }}"
            },
            init: function() {
                @if(isset($checkRoute))
                    this.on('addedfile', function(file) {
                        console.log(this.getAcceptedFiles())
                        fileCount++
                        if (filenameExists(file.name)) {
                            console.log(file.name)
                            existingFilenames.push(file.name)
                        }
                    })
                @endif
            },
            autoProcessQueue: false,
            sendingmultiple: function (files) {
                // Begin loading
                KTApp.blockPage({
                    overlayColor: '#000000',
                    type: 'v2',
                    state: 'success',
                    message: '{{ __('documents_uploading') }}'
                });
            },
            queuecomplete: function () {
                // End loading
                KTApp.unblockPage();

                $.notify({
                    // options
                    message: '{{ __('documents_upload_success') }}'
                }, {
                    // settings
                    type: 'success',
                    placement: {
                        from: "top",
                        align: "center"
                    },
                    animate: {
                        enter: 'animated fadeInDown',
                        exit: 'animated fadeOutUp'
                    },
                });

                window.location.replace("{{ $redirect }}");
            }
        });
    });

我关心的另一件事是我将如何在按下通知中的按钮时处理队列。

【问题讨论】:

  • 好吧,如果你将所有警告推送到一个数组中并一起打印?

标签: javascript dropzone.js dropzone


【解决方案1】:

我遇到了类似的问题,因为我想为用户提供服务器上不同上传目录的下拉列表。

由于每个目录都有不同的 acceptedFiles 规则集,因此静态选项 acceptedFiles 是不可能的。

相反,我结合收听 dropzone init 上的 drop 事件和“扩展”accept 功能:

drop 事件获取删除的文件总数并将其存储在droppedFilesCounter 中。它还初始化/重置一个全局对象dzCustomFeedback,并从先前的反馈中清除“反馈”区域。

每个拖放文件调用的扩展accept 函数检查当前选择的上传目录并将当前文件扩展名与配置接受的文件扩展名进行比较。

如果有匹配,done() 函数会“冒泡”和“全部清除”。

否则,文件将从预览列表中删除(或实际上永远不会进入其中),并且全局 dzCustomFeedback 对象会相应地为所有文件累积 invalidFileTypes 类型的错误消息。

一旦所有文件都通过 accept 函数 (droppedFilesCounter == 0) 运行并准备了一些反馈消息,就会调用 prepareFeedback 函数,它基本上使用累积的 jQuery <div> 容器填充dzCustomFeedback的内容。

init: function() {
  var myDropzone = this;

  myDropzone.on("drop", function(event) {

    if(typeof event.dataTransfer.files == 'object')
    {
      droppedFilesCounter = event.dataTransfer.files.length;
    }

    dzCustomFeedback = {};
    jQuery('#dz-feedback').empty();
  });
},
accept: function(file, done) {
    / * Erweiterung der vordefinierten accept Function * /
    customTypeSelector = document.getElementById("selectUploadFolder");
    var currentAcceptedFiles = customTypeAcceptedFiles[customTypeSelector.options[customTypeSelector.selectedIndex].value]
    var currentFileExtension = file.name.split(".").pop()

    droppedFilesCounter--;

    if (typeof customTypeAcceptedFiles[customTypeSelector.options[customTypeSelector.selectedIndex].value] == "object"
        &&
        jQuery.inArray(currentFileExtension, currentAcceptedFiles["extensions"] ) >= 0) {
        //accepted file
        done();
    }
    else {
        //Unaccepted file revert
        this.removeFile(file);
        if(typeof dzCustomFeedback["invalidFileTypes"] == "undefined")
        {
          dzCustomFeedback["invalidFileTypes"] = {
                                      "msg": [
                                                uploadDndConf["textElements"]["invalidFileTypesUploadFolder"].replace("{{uploadFolder}}", currentAcceptedFiles["label"])
                                              , currentAcceptedFiles["extensions"].join()
                                             ]
                                    , "type": "error"
                                    , "filesIgnored": {} };
        }
        dzCustomFeedback["invalidFileTypes"]["filesIgnored"][file.name] = file;
        done(this.options.dictInvalidFileType);
    }
    if(droppedFilesCounter == 0 && !jQuery.isEmptyObject(dzCustomFeedback))
    {
      prepareFeedback(dzCustomFeedback);
    }
},

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-07
    • 2019-03-07
    • 1970-01-01
    • 1970-01-01
    • 2018-02-20
    • 2012-02-10
    • 1970-01-01
    相关资源
    最近更新 更多