如何使文件上载与jQuery和xhr2一起使用(返回空的$ _FILES) [英] How to make file upload work with jQuery and xhr2 (empty $_FILES returned)
问题描述
我正在使用$ .ajax方法和xhr2使用$ .ajax方法上传文件.
I am using the $.ajax method and xhr2 to upload a file using the $.ajax method.
当我将任何标准对象分配给$ .ajax参数数据时,会在$ _POST(php)中返回适当的非空数组.
When I assing any standard object to the $.ajax parameter data, a proper non empty array is returned in $_POST (php).
JS:
data : {name:"john doe"}
PHP:print_r($ _ POST)
PHP: print_r($_POST)
Array
(
[name] => john doe
)
但是,当我将formData对象赋给参数数据以上传文件时,$ _ FILES(php)中会返回一个空数组
However, when I assing a formData object to the parameter data in order to upload a file, an empty array is returned in $_FILES (php)
JS:
data : new FormData(document.getElementById('fileupload'))
PHP:print_r($ _ FILES)
PHP: print_r($_FILES)
Array
(
)
我的html代码是:
<form enctype="multipart/form-data">
<div id="myform">
<input type="file" name="fileupload" id="fileupload" />
<div id="submit">UPLOAD</div>
</div>
</form>
我的jQuery代码是:
My jQuery code is:
$('#submit').click(function(){
var formData = new FormData(document.getElementById('fileupload'));
$.ajax({
url : "upload.php",
type: "POST",
data : formData,
xhr: function(){
myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function(data, textStatus, jqXHR){
console.log(data);
},
cache: false,
contentType : false,
processData: false
});
});
您是否会知道我的代码出了什么问题?我不知道为什么文件没有被上传.感谢您的帮助.
Would you happen to know what is wrong with my code? I can't figure out why the file is not being uploaded. Thanks for your help.
推荐答案
var element = document.getElementById("fileupload");
var myfiles= element.files;
var data = new FormData();
var i=0;
for (i = 0; i < myfiles.length; i++) {
data.append('file' + i, myfiles[i]);
}
$.ajax({
url: 'load.php',
type: 'POST',
contentType: false,
data: data,
processData: false,
cache: false
}).done(function(msg) {
//do something
});
源代码: http ://sw.solfin.net.co/index.php/programacion/php-y-jquery
这篇关于如何使文件上载与jQuery和xhr2一起使用(返回空的$ _FILES)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!