2012-07-16 76 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); 
     });