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



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

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

最新更新