使用$ _FILES变量访问通过AJAX发布的文件 [英] Access files posted through AJAX using $_FILES variable
问题描述
$。post
。但是我不能得到这个。 原因:当我发布数据(我想要上传的文件)时,我只能通过 $ _POST
全局,而不是必需的 $ _ FILES
全局。这里有一些我的代码真的很快:
< input type =fileid =file/>
< input type =submitid =submitvalue =Upload/> $(#file)。on(change,function(){
var file = this.files [0];
}
$(#submit ).click(function(){
var formData = new FormData();
formData.append('file',file);
$ .ajax({ b $ b url:'<?php echo BASE_URL;?> ajax / upload.php',//指向服务器端PHP脚本
dataType:'text',//期望从PHP脚本,如果有的话
cache:false,
contentType:false,
processData:false,
data:formData,
类型:'post',
成功:function(php_script_response){
alert(php_script_response); //显示来自PHP脚本的响应(如果有的话)
}
});
});
在PHP脚本中,当我 var_dump $ _POST
时,我得到这个文件,但是当我 var_dump $ _FILES
时,没有任何东西,我找到了这些资源,但是它们似乎不适合我:
$ _FILES
数组填充,内容类型应该是 multipart / form-data
尝试而不是:
contentType:false,
$ b $ $ p $ contentType:multipart / form-data,
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
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",
这篇关于使用$ _FILES变量访问通过AJAX发布的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!