我正在使用 AJAX 表单通过 ajax 在我的网站上上传个人资料图片,但问题是我无法做到这一点。我已经制作了一个 php 页面,其中表单将通过 ajax 发布。看看:
<?php
$file = $_FILES["file"];
$filename = $_FILES["file"]["name"];
$tempdir = $_FILES["file"]["tmp_name"];
$error = $_FILES["file"]["error"];
$type = $_FILES["file"]["type"];
$size = $_FILES["file"]["size"];
$maxsize = 524288;
$allowedtypes = array("image/png", "image/jpg", "image/jpeg", "image/bmp");
$errormsg = "";
if(!empty($error))
{
switch($error)
{
case '1':
$errormsg = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
break;
case '2':
$errormsg = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
break;
case '3':
$errormsg = 'The uploaded file was only partially uploaded';
break;
case '4':
$errormsg = 'No file was uploaded.';
break;
case '6':
$errormsg = 'Missing a temporary folder';
break;
case '7':
$errormsg = 'Failed to write file to disk';
break;
case '8':
$errormsg = 'File upload stopped by extension';
break;
default:
$errormsg = 'No error code avaiable';
}
} elseif(empty($tmpdir) || $tmpdir == 'none') {
$errormsg = 'No file was uploaded..';
} elseif(!in_array($type, $allowedtypes) || $size > $maxsize) {
$errormsg = 'Either image type not supported or size is extending 512 KB';
} else {
$filename = $_SESSION["username"];
$filename_array = explode(".",$_POST["filename"]);
$extension = array_pop($filename_array);
$path = 'folder/' . Utilities::GetDefaultPicturePath() . $filename . "." . $extension;
$location = $path . $filename;
move_uploaded_file($tmpdir, $location);
//for security reason, we force to remove all uploaded file
@unlink($file);
}
echo $errormsg;
?>
这是我的 AJAX:
<form action="admin/upload_profile_picture.php" method="post" class="hide" enctype="multipart/form-data" id="form">
<input type="file" id="file" class="hide" name="file" />
<input type="submit" name="submit" id="submit" />
</form>
由于表单被隐藏,因此通过另一个按钮调用提交:
<button class="btn btn-primary" onclick='submitForm();'>Save changes</button>
文件框的打开方式是:
<button class="btn btn-primary" id="upload">Upload</button>
这两个按钮的点击是通过这个脚本调用的:
$("#upload").click(function () {
$("#file").click();
});
$("#save").click(function () {
$("#submit").click();
});
最后,ajaxForm()
jquery 插件脚本在这里:
$('#form').ajaxForm(function (data) {
console.log(data);
});
正如您所看到的,我正在记录返回的数据。我在提交表单时总是得到的是“没有上传文件..”。正如您在我的 PHP 页面上看到的,仅当文件的临时目录为空或设置为“none”时,才会打印该错误。
那么问题是什么以及如何解决该问题。
谢谢。
最佳答案
将结果分配给第 4 行中的 $tempdir,然后检查下面的 $tmpdir
关于javascript - PHP 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20677393/