javascript - 如何通过拖放上传多个文件并使用ajax浏览

标签 javascript php jquery ajax file-upload

如何通过拖放上传多个文件并使用 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 />";   

最佳答案

您似乎只获得了要上传的第一个文件“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 到达您的元素

关于javascript - 如何通过拖放上传多个文件并使用ajax浏览,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53950415/

相关文章:

javascript - 如何去除div标签内容?

javascript - Typescript - 在解构构造函数中将属性设为公共(public)

php - 添加自定义错误页面后,Laravel 不显示调试消息

php - 获取某列数据以外的数据

javascript - 弹出窗口 jQ​​uery

javascript - 如何让弹出窗口显示一条消息,然后在 5 秒后显示下载,然后关闭弹出窗口

PHP 处理脚本未拾取图像

jquery - 将 List<int> 从模型传递到 jQuery int[]

php - jquery + php + json 有点迷失

javascript - HTML 结构不适用于不同的设备