JS - 拖放上传 - 限制拖动文件并允许点击拖放区打开 select 文件对话框

JS - Drag and drop upload - limiting dragged files and allowing click on drop zone to open select files dialog box

我已经使用拖放创建了一个文件上传系统,如下所示:

var dropzone = document.getElementById('dropzone');
var upload_button = document.getElementById('submit');
var files_to_upload;

upload_button.onclick = function(e){
    e.preventDefault();
    if(files_to_upload==''){
        files_to_upload = document.getElementById('new_file').files;
    }
    upload(files_to_upload);
}
function upload(files){
    var formData = new FormData();
    for(var i=0; i<files.length; i++){
        formData.append('file[]', files[i]);
    }
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function(){
        if(this.readyState == 4 && this.status == 200){
            console.log(this.responseText);
        }
    };
    xmlhttp.open("POST", "components/upload.php");
    xmlhttp.send(formData);
}
dropzone.ondrop = function(e){
    e.preventDefault();
    this.className = 'dropzone';
    files_to_upload = e.dataTransfer.files;
    var no_uploads = files_to_upload.length;
    this.innerText = no_uploads+' file(s) selected';
}
dropzone.ondragover = function(){
    this.className = 'dropzone active';
    return false;
}
dropzone.ondragleave = function(){
    this.className = 'dropzone';
    return false;
}
.dropzone{
  width:100%;
  height:200px;
  border:3px dashed LightGrey;
  line-height:200px;
  text-align:center;
  margin-bottom:10px;
}
.dropzone.active{
  border-color:DimGrey;
  color:DimGrey;
}
<form class="form mx-auto" method="POST" enctype="multipart/form-data">

<div class="form-group">
<label for="new_track">Upload Track</label>
<input class="form-control-file" type="file" name="new_file" id="new_file">
</div>

<div class="dropzone" id="dropzone">Drop file here to upload</div>

<button class="btn btn-success mt-3" name="submit" id="submit" onclick="return false;">Submit</button>

</form>

这很好用,并且可以正常工作。但是,我想改进一下,有几个问题:

  1. 如何限制拖放上传只允许一个文件?

  2. 而不是默认的 <input type="file"> 某些站点允许用户单击拖放区而不是打开对话框来选择文件。我该怎么做? (在正确的方向上一点就很好)

1)如何限制拖放上传只允许一个文件?

回答: 简单的解决方案是,在你的 ondrop 函数中这样做:

var no_uploads = files_to_upload.length;
if(no_uploads>1){
alert("Please upload only one file at a time");
files_to_upload = '';
 }
else
this.innerText = "your text";

2) 一些站点允许用户点击拖放区而不是打开对话框来选择文件,而不是默认设置。我该怎么做? (只要指向正确的方向就好了)?

回答: 在你的 ondrop 函数中做这样的事情:

  if(no_uploads>1){
  alert("Please upload only one file at a time");
  files_to_upload = ''; this.onclick = ""; this.style.cursor = "auto";
   }
  else{ 
  this.onclick = your_function_to_view_files(); 
  this.style.cursor = "pointer"; 
  this.innerText = "your text"; 
   }