拖放区.js - 接受选择框中的文件不起作用



我希望当用户更改他们从<select>元素中选择的选项时,能够更改 Dropzone 元素的acceptedFiles选项。有点像这段代码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,但它们都没有奏效。

这里的问题是,这两个选项都涉及在最后一次读取变量后更改变量。备选方案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 的文档中立即看到在创建放置区后编辑配置的方法,因此我建议您每次都使用新选项重新创建一个新的放置区,大致类似于(代码未测试(:

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"
});
};

最新更新