如何通过拖放方式上传多个文件并使用Ajax浏览? 下面的代码是我到目前为止所拥有的,并且运行良好,但是仅允许上传1个文件:
这是html:
<div id="drop_file_zone" ondrop="upload_file(event)" ondragover="return false">
<div id="drag_upload_file">
<p>DROP FILE HERE</p>
<p>or</p>
<p><input class="browse" type="button" value="Browse" onclick="file_explorer();"></p>
<input type="file" id="selectfile">
</div>
</div>
下面是我使用的带有ajax的javascript; :
var fileobj;
function upload_file(e) {
e.preventDefault();
fileobj = e.dataTransfer.files[0];
ajax_file_upload(fileobj);
}
function file_explorer() {
document.getElementById('selectfile').click();
document.getElementById('selectfile').onchange = function() {
fileobj = document.getElementById('selectfile').files[0];
ajax_file_upload(fileobj);
};
}
function ajax_file_upload(file_obj) {
if(file_obj != undefined) {
var form_data = new FormData();
form_data.append('file', file_obj);
$.ajax({
type: 'POST',
url: 'ajax.php',
contentType: false,
processData: false,
data: form_data,
success:function(response) {
//alert(response);
$(".success").html(response);
$('#selectfile').val('');
$('.myFiles').load(document.URL + ' .myFiles');
}
});
}
}
要上传的php:
$arr_file_types = ['image/png', 'image/gif', 'image/jpg', 'image/jpeg'];
if (!(in_array($_FILES['file']['type'], $arr_file_types))) {
echo "false";
return;
}
move_uploaded_file($_FILES['file']['tmp_name'], '../uploads/'. $_FILES['file']['name']);
echo "File uploaded successfully.<br /><br />";
答案 0 :(得分:2)
似乎您只有第一个文件上载“ e.dataTransfer.files [0]”。尝试更改为此:
function upload_file(e) {
e.preventDefault();
//here you can get all files
for (var i=0; i< e.dataTransfer.files.length;i++){
fileobj = e.dataTransfer.files[i];
ajax_file_upload(fileobj);
}
}
对于浏览,我想同样的逻辑是有效的
function file_explorer() {
document.getElementById('selectfile').click();
document.getElementById('selectfile').onchange = function() {
//here you can get all files
for (var i=0; i< e.dataTransfer.files.length;i++){
fileobj = document.getElementById('selectfile').files[i];
ajax_file_upload(fileobj);
}
};
}
如果导航不起作用,则可以尝试使用event.target https://developer.mozilla.org/en-US/docs/Web/API/Event/target
来到达您的元素