通过AJAX的FormData文件上传问题

问题描述:

我试图通过Ajax设置FormData对象执行图片上传,但是当提交表单数据时_FILES变量仍然为空并且 get HTTP_RAW_POST_DATA = [object Object]不确定问题出在哪里但真的很感谢这方面的帮助。通过AJAX的FormData文件上传问题

下面的代码片段:

<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); 
 
});

+0

尝试设置'dataType:'text'',你可以看到[这里](http://*.com/a/23981045/1959181) –

+0

还没有工作 – shinraken85

FORMDATA正在等待标准的JavaScript DOM对象和您使用的是jQuery对象

尝试使用

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

,而不是$(this)或者你也可以转换你的jQuery对象使用$(this)[0]