Access files posted through AJAX using $_FILES variable

泪湿孤枕 提交于 2019-12-24 14:28:19

问题


Trying to learn how to use the new AJAX file uploading, instead of using iframes or the good old PHP only file uploading. I understand how XHR requests work and have been using jQuery's $.post for a long time. But I can't get this one.

The reason: when I post data (the file I want to upload) I can only access it through a $_POST global, not the required $_FILES global. Here's some of my code real quick:

<input type="file" id="file"/>
<input type="submit" id="submit" value="Upload" />
$("#file").on("change",function () {
  var file = this.files[0];
}
$("#submit").click(function () {
  var formData = new FormData();
  formData.append('file',file);

  $.ajax({
    url: '<?php echo BASE_URL; ?>ajax/upload.php', // point to server-side PHP script 
    dataType: 'text',  // what to expect back from the PHP script, if anything
    cache: false,
    contentType: false,
    processData: false,
    data: formData,                         
    type: 'post',
    success: function(php_script_response){
      alert(php_script_response); // display response from the PHP script, if any
    }
  });
});

In the PHP script, when I var_dump $_POST, I'm getting the file, but when I var_dump $_FILES there's nothing there. I've found these resources but they don't seem to work for me:

  • AJAX File Upload with PHP, HTML5 File API and jQuery
  • jQuery AJAX file upload PHP
  • jQuery AJAX file upload

回答1:


In order to get the $_FILES array populated, content type should be multipart/form-data

Try instead of:

contentType: false,

Put:

contentType: "multipart/form-data",


来源:https://stackoverflow.com/questions/30943936/access-files-posted-through-ajax-using-files-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!