我在这里查看了几个答案,它们都使用 jQuery 的 .ajax()
方法。下面我有一个普通的 JS 方法,它是一个精简版本,我使用它并取得了一些成功。
function ajax(options){
var settings = {
method : 'POST',
url : 'endpoint.php',
data : null,
done : function(){},
fail : function(){},
complete : function(){}
};
if(options) for(option in options) settings[option] = options[option];
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if (xhttp.readyState == 4){
if(xhttp.status == 200){
settings.done(xhttp.responseText);
} else {
settings.fail(xhttp.responseText);
};
settings.complete(xhttp.responseText);
};
};
xhttp.open(settings.method, settings.url, true);
xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
xhttp.send(settings.data);
};
接下来是将文件分配给新的 FormData()
对象的函数。
function beginUpload(index){
var file = files.files[index];
var pkg = new FormData();
pkg.append('file', file);
pkg.append('size', file.size);
ajax({
data : pkg,
done : function(res){
console.log(res);
}
});
};
现在,问题来了:我找到的所有教程和示例都说,请求完成后,将在 $_FILES
全局变量中找到该文件。我执行 var_dump()
时得到 200 响应,并且 $_FILES
对我来说是空的,但 $_POST
不是。 $_POST
里面有看起来像文件的内容。检查了所有 php.ini 设置 from this question .
最佳答案
xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
不要这样设置。 XHR 将识别 FormData 对象并将其设置为正确的值(事实并非如此)。
关于javascript - 当 $_FILES 为空但 $_POST 有文件数据时处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36940391/