【问题标题】:How to throw error in dropzone for maxfilesize?如何在最大文件大小的 dropzone 中抛出错误?
【发布时间】:2018-05-24 10:07:05
【问题描述】:

在我的代码中,我将文件大小设置为 1mb ,它工作正常但没有抛出任何错误消息我该如何设置?

 $(document).ready(function () {

        $("#my-dropzone").dropzone({
            maxFiles: 1,
            maxFilesize: 1,
            parallelUploads: 1,
            url: "upload.php",


            success: function (file,response) {


                file.previewElement.classList.add("dz-success");

            },

            error: function (file,response) {
                sv.previewElement.classList.add("dz-error");
            }
        });
    });

【问题讨论】:

  • 只需将错误消息添加到错误回调中的divconsole.log

标签: javascript dropzone


【解决方案1】:

作为 dropzone 文档says

由于只能在 Dropzone 实例上监听事件, 设置事件监听器的最佳位置是在 init 函数中

所以设置 init 回调并在其中的 dropzone 实例中声明 successerror 回调:

$("#my-dropzone").dropzone({
    maxFiles: 1,
    maxFilesize: 1,
    parallelUploads: 1,
    url: "upload.php",
    init: function() {  // first you need an init callback
        success: function(file, response) {
            alert("Yeehaw!");
        },
        error: function(file, response) {  // and then can you have your error callback
            alert("Bah humbug...");
        }
    }
});

【讨论】:

    【解决方案2】:

    考虑这个等价的例子:

    try {
        var foo = function() {
            throw new Error("foo error");
        }
    }
    catch (error) {
    }
    
    foo();
    

    你不会期望调用 foo 导致的错误会被捕获,因为在定义 foo 时执行是在 try 块内。

    一种解决方案当然是在可能抛出的函数体内使用 try/catch,如您所展示的。另一种解决方案是创建一个可重用的“捕获包装器”函数,可能是这样的:

    function catchIfException(func, handler) {
        return function() {
            try {
                var args = Array.prototype.slice.call(arguments);
                func.apply(this, args);
            }
            catch (error) {
                handler(error);
            }
        };
    }
    
    
        $(document).on('change', 'select', 
            catchIfException(
                function(event) {
                    event.preventDefault();
                    event.stopPropagation();
    
                    throw new Error('callPage method failed');
                }, 
                function(error) {
                    console.log("error: " + error);
                }
            );
        );
    

    【讨论】:

      猜你喜欢
      • 2014-12-03
      • 1970-01-01
      • 1970-01-01
      • 2012-12-28
      • 1970-01-01
      • 1970-01-01
      • 2015-12-03
      • 2019-01-03
      • 1970-01-01
      相关资源
      最近更新 更多