动态更新 Dropzone maxFiles 设置

Dynamically update Dropzone maxFiles setting

Dropzone.options.dropzone = {
    uploadMultiple: false,
    maxFiles: {{ imagecount }},
    maxFilesize: 2, // MB
    dictFileTooBig: "That image is too large. We only allow 2MB or smaller.",
    acceptedFiles: ".jpeg, .jpg",
    init: function () {
        this.on("success", function(file, response) {
            $('.uploaded-photos').append('<div><img src="' + response.link + '"height="150" class="photo" id="' + response.id + '"/><span class="delete-photo">Delete</span></div>');
            $('.uploaded-photos').justifiedGallery('norewind')
            this.removeFile(file);

            var grabNewCount = parseInt($('.recordcount').text(), 10)
            $('.recordcount span').text(grabNewCount += 1);
            }); 
    }
};

我正在尝试动态更新 MaxFiles 属性 每次新图像 uploaded/deleted。

如您所见,我在页面加载时从我的服务器传递 {{ imagecount }}。这只是检查已为用户上传了多少图像,从而计算他们还剩下多少要上传。在第一页加载时,这有效。

当我删除我正在使用 AJAX 执行的图像时,问题似乎出现了。我似乎无法更新 maxFiles 值。如果我最初允许 10 张图片并且用户当前上传了 5 张并删除了一张,那么新的 maxFiles 值现在应该是 6,但我所做的任何事情似乎都不会影响动态更新该值。这是我的删除代码:

$('.delete-photo').click(function() {
    $(this).text('') // remove "delete" text from button
    $(this).html('<i class="fa fa-spinner fa-spin"></i>') // add spinning icon to indicate "working"

    var csrf = $('[name=csrfmiddlewaretoken]').val();
    $.ajax({
        context: this,
        type: "POST",
        url: '/delete-photo/',
        data: {'csrfmiddlewaretoken': csrf, 'id': $(this).parent().attr('id') },
        dataType: "json",
        timeout: 10000,
        cache: false,
        success: function(data, textStatus, XMLHttpRequest){
            var image = $(this).parent();
            $(image).fadeOut(800, function() {
                $(this).remove();
                $('.uploaded-photos').justifiedGallery()
            });
            Dropzone.options.dropzone.maxFiles = Dropzone.options.dropzone.maxFiles + 1;
            var grabNewCount = parseInt($('.recordcount').text(), 10)
            $('.recordcount span').text(grabNewCount -= 1);
                  }
    });
});

所以您可以看到我已经 Dropzone.options.dropzone.maxFiles = Dropzone.options.dropzone.maxFiles + 1; 尝试获取当前的 maxFiles 值并更新值 +1 但这没有做任何事情。

有什么想法吗?

所以我通过向表单标签添加数据属性并在每次删除或上传新图像时使用新数字更新该属性来实现此目的。

我的服务器端代码将初始最大文件数({{imagecount}} 标记)返回给加载页面:

<form data-count="{{ imagecount }}">

所以我打开的 dropzone 代码如下所示:

var maxFiles = $('.dropzone').attr('data-count'); Dropzone.options.dropzone = { uploadMultiple: false, maxFiles: maxFiles,

当有人通过 dropzone 上传图片时,在 .on(success) 函数中我有:

var imagecount = $('.dropzone').attr('data-count'); imagecount = imagecount - 1; $('.dropzone').attr('data-count', imagecount);

在删除 ajax 函数中我有:

var imagecount = $('.dropzone').attr('data-count'); imagecount = imagecount + 1; $('.dropzone').attr('data-count', imagecount);

经过几个小时的试验和错误,我意识到这个 maxFiles 设置并不像大多数人期望的那样工作:它只限制了可以从资源管理器上传或一次拖放的图像数量.重新打开资源管理器/页面重新加载后,可以上传更多文件。我也没有反映任何服务器故障,例如超过文件上传的文件大小。

此外,一旦 dropzone 被初始化,maxFile 设置就无法从另一个脚本更改。因此,当从 dropzone 外部的图库中删除文件时,maxFile 或图像的内部计数器无法增加。

在我的例子中,更好的解决方案被证明是阻止在服务器上上传过多的图像,在 uploader.php 来自 <form action="/uploader">

define('MAX_IMAGES', 10);
// Counting how many images already exist in the target directory
$imageCount = 0;
$fi = new FilesystemIterator($targetPath, FilesystemIterator::SKIP_DOTS);
foreach($fi as $fn) {
    $pathInfo = pathinfo($fn);
    $e = $pathInfo['extension'];

    if(in_array($e, array('jpg', 'jpeg', 'png', 'gif'))) {
        $imageCount++;
    }
}

if($imageCount >= MAX_IMAGES) {
    $success = false;
    $error = "Too many images";
    echo '{"name" : "'.$fileName.'", "success": "'.$success.'","extension" : "'.$fileExtension.'","dir_upload:":"'.$targetFolder.'","error":"'.$error.'","imageCount":"'.$imageCount.'"}';
    exit;
}

然后在 Dropzone 的 success 处理程序中,我有:

success: function (file, response) {
    var response_data = jQuery.parseJSON(response);
    if(!response_data.success) {
        errorFiles += 1;
        // Info about the error
        $(file.previewElement).addClass('dz-error').addClass('dz-complete').find('.dz-error-message').text(response_data.error);
    }
}

我希望对某人有所帮助。

MaxFiles 选项不应是动态的,并且不应取决于当前在 Dropzone 中的文件数。 它表示应允许在您的 Dropzone 实例中上传的文件总数。

正确的解决方案要简单得多:确保模拟文件(由服务器提供)包含 'Dropzone.ADDED' 和 'accepted: true' 的状态,如下所示:

var file = {
    name: value.name,
    size: value.size,
    status: Dropzone.ADDED,
    accepted: true
};

myDropzone.emit("addedfile", file);                                
myDropzone.emit("thumbnail", file, value.path);
myDropzone.emit("complete", file);
myDropzone.files.push(file);

虽然这在相当稀疏的文档中并不明显,但此处简要提及了 mockFiles 的附加说明: https://docs.dropzone.dev/configuration/basics/methods?q=mockFiles

但要点是:包括上面的 'status' 和 'accepted' 字段,以便您现有的服务器文件被视为“正确添加”并因此受到 maxFiles 的尊重 选项设置。

无需编写自定义 functions/logic 或表单属性等