2012-07-16 71 views
0

我正在使用html5和xhr进行多文件上传,正如您所看到的,我在循环中发送请求,这是一个糟糕的 概念,但我无法上传文件当我将它发送到循环之外并且只有最后一个文件被上传时。 我哪里错了?使用HTML5和XHR在codeigniter中多文件上传

$('#uploadimg').on('click', function(e) { 

    var files = document.getElementById('files').files; 

    var formData = new FormData(); 
    for (var i = 0; i < files.length; i++) { 
     formData.append('file', files[i]); 

     var xhr = new XMLHttpRequest(); 
     xhr.open('POST', 'http://localhost/ajaxuploader/upload/uploadimg'); 
     xhr.onload = function() { 
      if (xhr.status === 200) { 
       console.log('all done: ' + xhr.status); 
      } else { 
       console.log('Something went terribly wrong...'); 
      } 
     }; 

     xhr.send(formData); 

    } 

    // now post a new XHR request 
}); 

public function uploadimg(){ 

    $config['upload_path'] = FCPATH . 'uploads/' ; 
    $config['allowed_types'] = 'gif|jpg|png|jpeg|pdf|doc'; 

    $config['remove_spaces'] = 'TRUE'; 

    $this -> load -> library('upload', $config); 
    //$this->upload->initialize($config); 

    foreach ($_FILES as $k => $f) : 
     $this -> upload -> do_upload($k); 
    endforeach; 
    //$this->index(); 
} 
+0

快速10秒谷歌搜索返回:https://github.com/blueimp/jQuery-File-Upload/wiki/jQuery-File-Upload,-- -Multi-file-upload-with-CodeIgniter – gorelative 2012-07-16 13:34:50

+2

@Mike:这很有帮助,但它看起来像OP需要* this *代码的帮助(而且似乎并没有使用jQuery)。你的语气听起来有点不屑一顾。 – 2012-07-16 13:50:46

+0

我已经GOOGLE足够了,并且遇到了所有选项,上面的链接中的代码不起作用,那是我选择自己编码..我知道我在codeigniter中犯了一个错误,任何人都可以清除它? – Uma 2012-07-16 16:26:56

回答

0

它好像你应该看看的第一件事是你的for循环的js。 ID应该是独一无二的,所以我会将这种方法排除在外。

我可能会循环每个输入字段,检查是否attr类型==文件,然后将其附加到您的formData对象。

var inpts = document.getElementsByTagName('input');  

    for(var i=0; i < inpts.length; i++) 
    { 
     if(inpts[i].getAttribute('type') == 'file') 
     { 
      formData.append('myFiles[]', inpts[i].files[0]); 
     } 
    } 

在服务器端,我会看看你的foreach循环,也许for循环可能就足够了。

for($i=0; $i < count($_FILES); $i++){ 
    $this->upload->initialize(); //new initialization for each file 
    $this->upload->do_upload($_FILES[$i]); 
    continue; 
}; 
0

嗨,大家好,我想通过codeigniter工作正常,问题出现在jquery中。这是导致问题的线路。 “formData.append(files [i] .name,files [i]);”感谢所有为takign着力解决我的问题

$('#uploadimg').on('click', function(e) { 
      //console.log(files); 
      //    files = document.getElementById('files').files; 
      var formData = new FormData(); 
      $(files).each(function(i) { 
       formData.append(files[i].name, files[i]); 
      }) 
      var xhr = new XMLHttpRequest(); 
      xhr.open('POST', 'http://localhost/ajaxuploader/upload/uploadimg'); 
      xhr.onload = function(data) { 
       console.log(xhr.responseText); 
      }; 

      xhr.send(formData); 
     });