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