简体   繁体   English

用ajax上传多个文件

[英]Multiple files upload with ajax

I'm trying to make a script to upload multiple files using ajax, and print them on the screen with a loading circle display. 我正在尝试制作一个脚本,以使用ajax上传多个文件,并使用加载圆圈显示将它们打印在屏幕上。

The script is working for one file, but I have a problem to make it works for multiple files. 该脚本适用于一个文件,但是我很难使它适用于多个文件。 I guess it a "scope" problem. 我猜这是一个“范围”问题。 But my JS knowledge is not that good. 但是我的JS知识不是那么好。

Also, I'm only using standard JS, no jQuery. 另外,我只使用标准的JS,没有jQuery。

Here's the script : 这是脚本:

var index_div = 0;
var dropper = document.querySelector('#upload');

dropper.addEventListener('dragover', function(e) {
        e.preventDefault(); // Annule l'interdiction de "drop"
    }, false);

dropper.addEventListener('dragenter', function() {
    dropper.style.borderStyle = 'solid';
});

dropper.addEventListener('dragleave', function() {
    dropper.style.borderStyle = 'dashed';
});

dropper.addEventListener('drop', function(e) {
    e.preventDefault();
    dropper.style.borderStyle = 'dashed';
    var files = e.dataTransfer.files,
        filesLen = files.length;
    for (var i = 0 ; i < filesLen ; i++) {
    var NomImage = files[i].name;
    if(files[i] != '')
    {
    if(window.XMLHttpRequest)
    {
        xhr=new XMLHttpRequest();
    }
    else if(window.ActiveXObject)
    {
        xhr=new ActiveXObject("Microsoft.XMLHTTP");
    }
    var newDiv = document.createElement("div");
    newDiv.setAttribute("class","image_div");
    document.getElementById("upload").appendChild(newDiv); 
    document.getElementsByClassName("image_div")[index_div].innerHTML = '<img id="chargement" src="../includes/chargement.gif"/>';
    var form = new FormData();
    form.append('file', files[i]);
    xhr.open('POST', "./traitement_upload.php", true);
    xhr.onload = function (e) {
    if(xhr.readyState==4 && xhr.status==200)
    {
        document.getElementsByClassName("image_div")[index_div].innerHTML = 
xhr.responseText;
        index_div += 1;
    }
    }
    xhr.send(form);
    }
    }

});

Sorry for the sloppy code. 对不起,草率的代码。 If I check the xhr readyState and status during the loop, the first(s) are 1 and 0, then the last one is good. 如果在循环期间检查xhr readyState和状态,则第一个为1和0,那么最后一个为好。

You can see I'm creating a new div for each uploaded file so I can print a thumbnail in it. 您会看到我正在为每个上传的文件创建一个新的div,因此我可以在其中打印缩略图。

For what I understand, the code is processing while the ajax request is not done yet. 据我了解,代码正在处理而ajax请求尚未完成。 The result is I only see the last file I submitted. 结果是我只看到我提交的最后一个文件。

If I put a false to the async flag on xhr.open, it works but it doesn't show the loading gif of course. 如果我在xhr.open上的async标志上添加了false,它可以工作,但是它当然不会显示加载的gif。

Thank you for your help. 谢谢您的帮助。

You should extract the code for AJAX functionality in a separate function - otherwise the closure for xhr.onload will use the current (at the time of calling) value of index_div - most probably the last one from the FOR cycle. 你应该提取AJAX功能的代码在一个单独的功能-否则为封xhr.onload将使用当前的(在通话的时间)的值index_div -最有可能从最后一个周期。 Also, querySelector returns a collection - even if it finds just a single element, or even if it finds nothing. 同样, querySelector返回一个集合-即使它只找到一个元素,或者什么也没找到。 Also, you should use both event.dataTransfer and event.target in order to handle both drag/drop and normal clicking. 另外,您应同时使用event.dataTransferevent.target来处理拖放和常规单击。

var dropper = document.getElementById('upload');

dropper.addEventListener('dragover', function(e) 
{
  e.preventDefault();
    dropper.style.background = '#eee';
}, false);

dropper.addEventListener('dragenter', function() 
{
  e.preventDefault();
    dropper.style.background = '#eee';
}, false);

dropper.addEventListener('dragleave', function() 
{
  e.preventDefault();
    dropper.style.background = '#fff';
}, false);

dropper.addEventListener('drop', uploadFile, false);
document.getElementById('file_upload').addEventListener('change', uploadFile, false);

function uploadFile(e) 
{
  e.preventDefault();
    dropper.style.background = '#fff';
    dropper.style.borderStyle = 'dashed';
    var files = (e.dataTransfer || e.target).files,
        filesLen = files.length;
    for (var i = 0 ; i < filesLen ; i++) 
    {
        if(files[i] != '')
        {
            var newDiv = document.createElement("div");
            newDiv.setAttribute("class","image_div");
            newDiv.innerHTML = '<img id="chargement" src="../includes/chargement.gif"/>';
            document.getElementById("upload").appendChild(newDiv); 

        doAJAX(newDiv,files[i]);
      }
    }
}

function doAJAX(div,file)
{
  var form = new FormData();
  form.append('file', file);

  if(window.XMLHttpRequest)
  {
      xhr=new XMLHttpRequest();
  }
  else if(window.ActiveXObject)
  {
      xhr=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xhr.open('POST', "./traitement_upload.php", true);
  xhr.onload = function (e) 
  {
    if(xhr.readyState==4 && xhr.status==200)
    {
      div.innerHTML = xhr.responseText;
    }
  }
  xhr.send(form);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM