首页 > 解决方案 > Dropzone.js - 从选择框中接受的文件不起作用

问题描述

当用户更改他们从元素中选择的选项时,我希望能够更改acceptedFilesDropzone 元素的选项<select>。有点像这段代码Dropzone.options.myDropzone = { acceptedFiles: selected_value};

到目前为止,我尝试了两种方法:

HTML 选择框:

<select class="form-control" id="cond_file_type" name="cond_file_type">
    <option>-- File Type --</option>
    <option value="pdf">PDF</option>
    <option value="docx">DOCX</option>
    <option value="xlsx">XLSX</option>
    <option value="png">PNG</option>
    <option value="jpg">JPG</option>
    <option value="gif">GIF</option>
</select>

Javascript:

// Attempt 1
document.getElementById("cond_file_type").onchange = function(){
    var file_type = '.' + this.options[this.selectedIndex].value;

    Dropzone.options.myDropzone = {
        acceptedFiles: file_type,
    };
};


// Attempt 2
var file_type = '';
document.getElementById("cond_file_type").onchange = function () {
    file_type = '.' + this.options[this.selectedIndex].value;
};
Dropzone.options.myDropzone = {
    acceptedFiles: file_type,
};

我尝试了 1 和 2,但它们都没有工作。

标签: javascriptdropzone.jsdropzone

解决方案


这里的问题是,这两个选项都涉及在最后一次读取变量后更改变量。选项 2 在这方面最具指导意义;执行脚本时会发生以下情况:

// file_type is set to ''
var file_type = '';
document.getElementById("cond_file_type").onchange = function () {
    // This line is not run until later when the user changes the select box.
    file_type = '.' + this.options[this.selectedIndex].value;
};
// So file_type is still set to ''
Dropzone.options.myDropzone = {
    // accepted files is set to '', regardless of what the user later selects.
    acceptedFiles: file_type,
};

然而,即使在选项 1 中,该Dropzone.options对象也只会在第一次创建 dropzone 时被读取,因此一旦页面加载,仍然没有必要对其进行编辑。

我无法立即从 Dropzone 的文档中看到在创建 dropzone 后编辑配置的方法,因此我建议您每次都使用新选项重新创建一个新的 dropzone,大致类似于(代码未测试):

document.getElementById("cond_file_type").onchange = function () {
    // This line is not run until later when the user changes the select box.
    var file_type = '.' + this.options[this.selectedIndex].value;
    var myDropzone = new Dropzone("div#myDropzonesId", {
        acceptedFiles: file_type,
        url: "/file/post"
    });
};

推荐阅读