【问题标题】:FormData file upload issue via AJAX通过 AJAX 上传 FormData 文件的问题
【发布时间】:2017-05-14 00:26:14
【问题描述】:

我正在尝试通过 Ajax 设置 FormData 对象执行图像上传,但是当提交表单数据时,_FILES 变量保持为空并且 get HTTP_RAW_POST_DATA=[object Object] 不确定问题出在哪里,但非常感谢您对此的帮助。

下面的代码sn-ps:

<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>

刚刚将 Javascript 修改为以下内容,现在似乎可以正常工作了。 只是不适用于 Jquery。

$('#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);
});

【问题讨论】:

  • 尝试设置dataType: 'text',如你所见here
  • 不行还是不行

标签: php ajax forms file upload


【解决方案1】:

FormData 正在等待一个标准的 javascript DOM 对象,而您正在使用一个 jQuery 对象

尝试使用

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

代替$(this) 或者您也可以使用$(this)[0] 转换您的jQuery 对象

【讨论】:

    猜你喜欢
    • 2016-08-02
    • 1970-01-01
    • 1970-01-01
    • 2018-12-18
    • 2010-11-12
    • 2019-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多