2016-02-04 554 views
1

我試圖通過AJAX使用簡單的HTML表單上傳圖像,包括input[type='file']元素和formData(),但是當我檢查formData()時,它看起來是空的,沒有任何內容被傳遞到服務器。使用AJAX上傳文件

jQuery的

//Dynamically loaded form 

$(document).on('submit', '.update-form', function(e) { 
    e.preventDefault(); 
    var form = $(this); 

    amendDatabase(form); 
}); 

function amendDatabase(form) { 
    var formData = new FormData(form); 
    console.log(formData); //This produces 'formData: No properties' 

    var url = 'file.php'; 

    request = $.ajax({ 
     url:   url, 
     method:   'post', 
     data:   formData, 
     processData: false, 
     contentType: false 
    }); 

    request.done(function(data) { 
     console.log(data); //This produces an empty/blank return 
    }); 
} 

file.php

function uploadFile() { 
    echo 'formData was passed to server'; 
} 

uploadFile(); 

HTML

<form class="update-form" id="add-file" enctype="multipart/form-data"> 
    <label for="image">Product image</label> 
    <input type="file" id="image" name="image" multiple="multiple"> 
    <div class="hidden-holder"> 
     <input type="hidden" id="action" name="action" value="file"> 
    </div> 
    <div class="submit-holder"> 
     <input type="submit"> 
    </div> 
</form> 
+0

你看過了參數嗎? –

+0

@CharlotteDunois你指的是哪個參數? – Ryan

回答

-1

你應該附加文件形成數據:

// Create a formdata object and add the files 
    var data = new FormData(); 
    $.each(files, function(key, value) 
    { 
     data.append(key, value); 
    }); 

$.ajax({ 
     url: 'submit.php?files', 
     type: 'POST', 
     data: data, 
     cache: false, 
     dataType: 'json', 
     processData: false, // Don't process the files 
     contentType: false, // Set content type to false as jQuery will tell the server its a query string request 
+0

我已經使用var formData = new FormData(form);''form'是我的表單數據,所以我不認爲這有什麼區別。 – Ryan

0

從阿賈克斯直接上傳文件僅適用於使用直接AJAX使用這個插件的新browser.insteat:http://malsup.com/jquery/form/

$(document).ready(function() { 
    $('#add-file').ajaxForm(function() { 
       alert("Upload Done!"); 
    }); 
}); 
你沒有改變你的HTML的任何