2017-05-22 41 views
1

我從這裏得到:https://www.raymondcamden.com/2013/10/01/MultiFile-Uploads-and-Multiple-Selects如何傳遞使用XMLHttpRequest上傳的圖片?

我嘗試第二個代碼

在handleform,我改變這樣的:

function handleForm(e) { 
     e.preventDefault(); 
     var data = new FormData(); 

     for(var i=0, len=storedFiles.length; i<len; i++) { 
      data.append('files', storedFiles[i]); 
     } 

     var xhr = new XMLHttpRequest(); 
     xhr.open('POST', 'data_post.php', true); 

     xhr.onload = function(e) { 
      if(this.status == 200) { 
       console.log(e.currentTarget.responseText); 
       alert(e.currentTarget.responseText + ' items uploaded.'); 
      } 
     } 

     xhr.send(data); 
    } 

在我data_post.php是這樣的:print_r($_POST);

我選擇一些圖像並提交,結果是這樣的空陣列:

Array () 

爲什麼結果是空的?

+0

的可能的複製[jQuery的AJAX文件上傳PHP(https://stackoverflow.com/questions/23980733/jquery-ajax-file-upload-php) – Webinion

+0

@samuel你必須張貼FORMDATA。 –

+0

@Pandhi Bhaumik,這是多個圖像。這是不同的 –

回答

1

這是工作AJAX的解決方案有多個文件的PHP代碼。
您可以將整個代碼複製/粘貼到本地主機或服務器進行測試。

<?php 
if($_FILES) { 

    if(is_array($_FILES['img']['name'])) { 
    foreach($_FILES['img']['name'] as $key => $value) { 
     // upload path is the same directory as this file 
     move_uploaded_file($_FILES["img"]["tmp_name"][$key], $_FILES['img']['name'][$key]); 
    } 
    } 

// test output 
    echo "<pre>"; 
    print_r($_FILES); 
    echo "</pre>"; 

    die(); 
} 
?> 


<script> 
// on document ready 
document.addEventListener("DOMContentLoaded", function(){ 

    document.getElementById("handleForm").addEventListener("click",function() { 
    var formData = new FormData(document.getElementById("form")); 

    for(var i = 0; i < document.getElementById("img").files.length; i++) { 
     console.log(i) 
     formData.append("img[]",document.getElementById("img").files[i]); 
    } 

    var xhr = new XMLHttpRequest(); 
    // here you can change empty URL to your file 
    xhr.open("POST", ""); 
    xhr.send(formData); 
    }); 

}); 
</script> 

<form action="" method="post" enctype="multipart/form-data" id="form"> 
    <input type="file" name="img" id="img" multiple /> 
    <div style="padding: 5px 10px; border: 1px solid black; cursor: pointer; display: inline-block" id="handleForm" >Send</div> 
</form> 
1

追加文件後,必須發佈表單數據

var file_data = $('#sortpicture').prop('files')[0]; 
var form_data = new FormData();     
form_data.append('file', file_data); 
alert(form_data);        
$.ajax({ 
      url: 'upload.php', 
      dataType: 'text', 
      cache: false, 
      contentType: false, 
      processData: false, 
      data: form_data,       
      type: 'post', 
      success: function(php_script_response){ 
       alert(php_script_response); 
      } 
});