2015-03-19 142 views
0

HTMLAjax文件上傳。發送FORMDATA

<form id="uploadimage" action="" method="post" enctype="multipart/form-data"> 
     <div class="file-input btn btn-block btn-primary"> 
      + add files 
      <input type="file" name="files" id="image_upload" > 
     </div> 
    </form> 

JS

$('#image_upload').change(function(){ 
var formdata = $(this).parent().parent(); 
$.ajax({ 
    url: "/server.php", // Url to which the request is send 
    type: "POST",    // Type of request to be send, called as method 
    data: new FormData(formdata), // Data sent to server, a set of key/value pairs (i.e. form fields and values) 
    contentType: false,  // The content type used when sending data to the server. 
    cache: false,    // To unable request pages to be cached 
    processData:false,  // To send DOMDocument or non processed data file it is set to false 
    success: function(data) // A function to be called if request succeeds 
    { 
     alert(data);       
    } 
}); 

Server.php

if(isset($_FILES["file"]["type"])) 
     { 
      echo "YES"; 
     } 
     else echo "NO"; 

我tryied做不同的事情,但繼續得到NO作爲答案。 任何方式來獲得積極的答案?

回答

1

您正在將一個jQuery對象傳遞給您的FromData構造函數,該構造函數接受一個表單。
當你通過它時從jQuery對象中公開表單

data: new FormData(formdata[0]), // Data sent to server, a set of key/value pairs (i.e. form fields and values) 
+0

太棒了!非常感謝你! – David 2015-03-20 05:27:04