[英]PHP Ajax Image Upload bug
我现在尝试使我的Ajax图像上传正常工作。 但可惜的是它不起作用,我找不到原因。
<script>
$(document).ready(function() {
$("#uploadBTN").click(function(event) {
event.preventDefault();
var tmp_form = $("#fileinfo")[0];
var fd = new FormData(tmp_form);
$.ajax({
url: './ajax/image_post_upload.php',
type: 'POST',
data: fd,
async: true,
success:function(data){
$('#output').html(data);
},
cache: false,
contentType: false,
processData: false
});
});
});
</script>
<form id="fileinfo">
<input id="fileinfo" name="userImage" type="file" class="file" />
<div id="uploadBTN">SUBMIT</div>
</form>
<div id=output>LOG HERE</div>
image_post_upload.php
<?php
if(isset($_FILES['file'])){
$filename = $_FILES['file']['name'];
if(isset($_FILES['file']['name']) && !empty($filename)){
$target_dir = "./UPLOADS/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["file"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["file"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
$root = getcwd();
if (move_uploaded_file($_FILES["file"]["tmp_name"], $root.$target_file)) {
echo "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}else{
echo 'please choose a file';
}
}else{
echo 'not set';
}
?>
此刻它每次都说不定吗? 我的脚本有什么问题?
您用于文件输入的HTML name
属性与PHP $_FILES['file']
不匹配,这就是为什么if(isset($_FILES['file']))
返回false的原因。
您可以通过更改HTML以使其与PHP匹配来解决此问题:
<input id="fileinfo" name="file" type="file" class="file" />
希望有帮助!
您的文件输入名称为userImage,并且正在以$_FILES['file']
身份进行访问,
因此,请使用下面两个代码中的任何一个。
HTML: <input id="fileinfo" name="userImage" type="file" class="file" />
PHP: $_FILES['userImage']
HTML: <input id="fileinfo" name="file" type="file" class="file" />
PHP: $_FILES['file']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.