Ajax无法发送文件(jpg-png)。我无法解决问题。
表单代码
<form action="upload.php" method="post" enctype="multipart/form-data">
<label for="img">
<button id="post-img">update</button>
<!-- input hidden !! -->
<input type="file" name="img" id="a-img" style="visibility:hidden">
</label>
AJAX:
$('#a-img').change(function(){
var photo = $('form').serialize();
$.ajax({
url:'upload.php',
data: photo,
success:function(data){
alert(data);
}
});
});
php代码:
if($_FILES){
echo "file ok";
}else{
echo "no file";
}
回调:“没有文件”;
答案 0 :(得分:2)
将id frm_send_img添加到表单。
<form action="upload.php" id="frm_send_img" method="post" enctype="multipart/form-data">
<label for="img">
<button id="post-img">update</button>
<!-- input hidden !! -->
<input type="file" name="img" id="a-img" style="visibility:hidden">
</label>
更改下面的脚本。
$('#a-img').change(function(){
var photo = new FormData($("#frm_send_img")[0]);
$.ajax({
url: "upload.php",
type: "POST",
data: photo,
async: false,
success: function (msg) {
alert(msg)
},
cache: false,
contentType: false,
processData: false
});
e.preventDefault();
});
答案 1 :(得分:1)
你可以这样做:
$('#a-img').change(function(){
var frmData = new FormData();
frmData.append('file', $('#a-img')[0].files[0]);
$.ajax({
method: "POST",
url: "upload.php",
data: frmData,
}).done(function (msg) {
//logic after success
});
您可以照常访问服务器上的图像:
if (isset($_FILES["img"]["name"]) && $_FILES["img"]["name"] != "") {
echo "image validation and uploading";
}else{
echo "no file uploaded";
}