dropzone 仅上传一个文件

问题描述 投票:0回答:8

我使用 dropzone.js 作为我的拖放文件上传解决方案。我只想上传一个文件,如果我上传第二个文件,则应删除第一个文件,并上传第二个文件。 知道怎么做吗..

这是我的html

<form class="dropzone dz-clickable" action="upload.php" enctype='multipart/form-data'>
  <i class="fa fa-cloud-upload element"></i>
  <div style="color:gray;">Drag and drop or click to upload image</div>
  <input type="hidden" name="filenameEmail" class="filenameEmail" value="">
  <input type="hidden" name="side" value="front">
</form>

我改变了dropzone.js

maxFiles: 1

它只允许上传一个文件,但我无法删除以前上传的文件。请帮助我。提前致谢

javascript php dropzone.js
8个回答
102
投票

maxFiles: 1 用于告诉 dropzone 应该只有一个文件。当文件超过 1 个时,将调用函数 maxfilesexceeded,超出的文件作为第一个参数。

这是一个简单的功能,可以删除第一个文件的预览并添加新的:)

maxFiles:1,
init: function() {
      this.on("maxfilesexceeded", function(file) {
            this.removeAllFiles();
            this.addFile(file);
      });
}   

32
投票

我将事件

maxfilesexceeded
与方法
addFile
结合使用,并陷入事件调用的无限循环。应该是使用
addFile
的问题,因为我在官方网站或GitHub wiki中都没有看到提到它。最后我用
addedfile
事件解决了。 Dropzone.js是我写的时候的最新版本(4.3.0)。

init: function() {
  this.on('addedfile', function(file) {
    if (this.files.length > 1) {
      this.removeFile(this.files[0]);
    }
  });
}

19
投票

maxFiles
限制为 1 仍允许在上传对话框中选择多个文件。要禁止在配置中选择多个图像,请指定以下初始化函数:

maxFiles:1,
init: function() {
    this.hiddenFileInput.removeAttribute('multiple');
}  

3
投票
 Dropzone.prototype.defaultOptions.init = function () {

                 this.hiddenFileInput.removeAttribute('multiple');
                 this.on("maxfilesexceeded", function (file) {
                     this.removeAllFiles();
                     this.addFile(file);
                 });
             };

这对我来说是工作。


0
投票

两种解决方案的组合在 init 函数中为我完成了工作:

        this.on("addedfile", function (file) {
            if (this.files.length > 1) {
                this.removeAllFiles()
                this.addFile(file);
            }
        });

0
投票

这对我有用

const dropzoneInput = document.querySelectorAll('.dz-hidden-input')
for (const input of dropzoneInput) {
    if (input.getAttribute('multiple')) {
        input.removeAttribute('multiple')
    }
}

它的作用是验证 dropzone 输入是否具有 multiple 属性,如果有,则删除 id

注意:类 .dz-hidden-input 对您来说可能不同。


0
投票

这里的许多解决方案都接受两个文件,但上传哪个文件有点随机。更好的方法是通知用户。

init: function () {
    this.on('addedfile', function () {
        if (this.files.length > 1) {
            this.removeAllFiles();
            alert('Drop only one file');
        }
    });
}

注意:

maxFiles
不是必需的,因为我们在这里不使用
maxfilesexceeded
。只需相应地设置
this.files.length > 1
即可。


-1
投票

这些解决方案都不适合我。

maxfilesexceeded
事件被调用得太晚,即在尝试添加文件之后。

使用

this.removeFile(this.files[0]);
的其他解决方案导致
"Uncaught TypeError: Cannot read property 'removeChild' of null".
或无限循环。

已解决 -

maxFiles: 2,
init: function () {

    this.on("addedfile", function (file) {
        if (this.files.length > 1) {
            this.files = this.files.slice(1, 2);                        
        }
    });

}

使用

dz-clickable
(文件选择器 btn)并拖放时有效。

© www.soinside.com 2019 - 2024. All rights reserved.