FormData文件上传问题通过AJAX

时间:2016-12-29 16:41:21

标签: php ajax forms file upload

我试图通过Ajax设置FormData对象来执行图像上传,但是当提交表单数据时,_FILES变量仍为空并且 得到HTTP_RAW_POST_DATA = [object Object]不知道这里有什么问题,但我真的很感激一些帮助。

下面的代码段:



<form id="test_upload_form" action="/inventory/fileImport">
    <input id="test_file" type="file" name="superfile">
    <input type="hidden" name="nonce" value="<?=$this->nonceField()?>">
    <input type="submit" name="submit">
</form>
<script>
    $('#test_upload_form').on('submit', function(e){

        e.preventDefault();
        var fileInput = $('#test_file');
        debugger;
        var file = ($('#test_file'))[0].files[0];
        var formData = new FormData($(this));
        formData.append('file', file);
        $.ajax({
            url: '/inventory/fileImport',
            type: 'POST',
            data: formData,
            cache: false,
            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
            success: function(data, textStatus, jqXHR)
            {
                if(typeof data.error === 'undefined')
                {
                    console.log(data);
                }
                else
                {
                    // Handle errors here
                    console.log('ERRORS: ' + data.error);
                }
            },
            error: function(jqXHR, textStatus, errorThrown)
            {
                // Handle errors here
                console.log('ERRORS: ' + textStatus);
                // STOP LOADING SPINNER
            }
        });
    });
</script>
&#13;
&#13;
&#13;

刚刚将Javascript修改为以下内容,现在似乎正在运行。 只是不和Jquery合作。

&#13;
&#13;
$('#test_upload_form').on('submit', function(e){
        e.preventDefault();
        var file = ($('#test_file'))[0].files[0];
        var formData = new FormData(document.getElementById("test_upload_form"));
        formData.append('file', file);
        var request = new XMLHttpRequest();
        request.open("POST", "/inventory/fileImport");
        formData.append("serialnumber", 'asdasdsadas');
        request.send(formData);
});
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

FormData正在等待标准的javascript DOM对象,并且您正在使用jQuery对象

尝试使用

var formData = new FormData(document.getElementById("test_upload_form"));

代替$(this),或者您也可以使用$(this)[0]

转换jQuery对象