我在网上搜索了使用 ajax 进行 PHP 图像上传的代码 。 我找到了下面的代码 。 问题是我更改了几件东西( 最小 tweaks), 使服务器上的工作正常。 最初它只是处理从表格中发布的数据的php 页面( 不是一个分类或函数) 。 我将其转换成类功能 。 我现在正在跟踪 OOP 。 我认为将程序转换为 OOP 的最佳方法就是将 $_ FILES 和 $_ POST 转换为一种方法, 并在内部处理它们。 我认为这行不通 。 看看这个示例, 请就如何前进提出建议 。
function uploadImageChosen($_FILES, $_POST){
$path = "../uploads/images/";
$valid_formats = array("jpg", "png", "gif", "bmp");
$connectionInstance = new ConnectionClass();
$connectionInstance->connectToDatabase();
$imgName;
$imgURL;
$imgSize;
$imgDir = $_POST[ directory ];
if(isset($_POST) and $_SERVER[ REQUEST_METHOD ] == "POST")
{
$name = $_FILES[ photoimg ][ name ];
$imgSize = $_FILES[ photoimg ][ size ];
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$imgName = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$tmp = $_FILES[ photoimg ][ tmp_name ];
if(move_uploaded_file($tmp, $path.$imgName))
{
$imgURL = $path.$imgName;
$connectionInstance->query("INSERT INTO imagesupload(id, title, url, size, directory) VALUES (null, $imgName , $imgURL , $imgSize , $imgDir )");
//echo "<img src= uploads/".$imgName." class= preview >";
}
else{
echo "failed";
}
}else{
echo "Image file size max 1 MB";
}
}else{
echo "Invalid file format..";
}
}else{
echo "Please select image..!";
}
}//end of if
}//end of function
至于排序函数的调用页面,这里是:
<?php
require_once("../classes/UploadImages.php");
$uploadInstance = new UploadImages();
$uploadInstance->uploadImageChosen($_FILES, $_POST);
//header("LOCATION:portfolio.php");
?>
非常感谢:)