我正在尝试使用ajax上传图像文件而不刷新页面但文件不会移动到指定文件夹我做了非常基本的文件上传php代码以避免错误并在以后开发
if($_SERVER["REQUEST_METHOD"]=="POST"){
$file = $_FILES["uploaded"]
$target_dir = "user_image/";
$target_file = $target_dir . basename($_FILES["uploaded"]["name"]);
move_uploaded_file($_FILES["uploaded"]["tmp_name"],$target_file);
}
我的ajax和JavaScript工作正常,但目标文件上没有图像user_image /
<script charset="UTF-8">
function _(id){
return document.getElementById(id);
}
_("file_upload").onchange = function() {
//_("file_upload").submit();
var id = _("user_id").innerHTML;
var file = _("file_upload").files[0];
var formdata = new FormData();
formdata.append("file1",file);
var ajax = new XMLHttpRequest();
ajax.onreadystatechange =
function(){
if(ajax.readyState==4 && ajax.status==200){
_("one").remove();
var img = document.createElement('img');
var first_path = '/user_image/';
var path = first_path.concat(id,'.png');
img.setAttribute('alt','User image');
img.setAttribute('id','one');
img.setAttribute('src',path);
_("user").appendChild(img);
alert("end");
}
else{
_("one").remove();
var img = document.createElement('img');
img.setAttribute('src','/img/loading.gif');
img.setAttribute('alt','User image');
img.setAttribute('id','one');
_("user").appendChild(img);
}
}
ajax.open("POST","upload_image.php");
ajax.send(formdata);
};
</script>
答案 0 :(得分:2)
您需要更改请求标头才能使其正常工作。
ajax.setRequestHeader("Content-type", "multipart/form-data");