脚本的构造如下:
// Function For Image Upload
public function storeUploadedImage($image) {
if ($image['error'] == UPLOAD_ERR_OK) {
// Does the Document object have an ID?
if (is_null($this->id))
trigger_error("Document::storeUploadedImage(): Attempt to upload an image for an Document object that does not have its ID property set.", E_USER_ERROR);
// Delete any previous image(s) for this Document
$this->deleteImages();
// Get and store the image filename extension
$this->imgExtension = strtolower(strrchr($image['name'], '.'));
// Store the image
$tempFilename = trim($image['tmp_name']);
if (is_uploaded_file ($tempFilename)) {
if (!(move_uploaded_file($tempFilename, $this->getImagePath())))
trigger_error("Document::storeUploadedImage(): Couldn't move uploaded file.", E_USER_ERROR);
if (!(chmod($this->getImagePath(), 0666)))
trigger_error("Document::storeUploadedImage(): Couldn't set permissions on uploaded file.", E_USER_ERROR);}
// Get the image size and type/Extension
$attrs = getimagesize ($this->getImagePath());
$imageWidth = $attrs[0];
$imageHeight = $attrs[1];
$imageType = $attrs[2];
// Load the image into memory
switch ($imageType) {
case IMAGETYPE_GIF:
$imageResource = imagecreatefromgif ($this->getImagePath());
break;
case IMAGETYPE_JPEG:
$imageResource = imagecreatefromjpeg ($this->getImagePath());
break;
case IMAGETYPE_PNG:
$imageResource = imagecreatefrompng ($this->getImagePath());
break;
default:
trigger_error ("Document::storeUploadedImage(): Unhandled or unknown image type ($imageType)", E_USER_ERROR);
}
// Copy And Resize The Image To Create The Thumbnail
$thumbHeight = intval ($imageHeight / $imageWidth * 120);
$thumbResource = imagecreatetruecolor (120, $thumbHeight);
imagecopyresampled($thumbResource, $imageResource, 0, 0, 0, 0, 120, $thumbHeight, $imageWidth, $imageHeight);
// Save the Image thumbnail
switch ($imageType) {
case IMAGETYPE_GIF:
imagegif ($thumbResource, $this->getImagePath("thumb"));
break;
case IMAGETYPE_JPEG:
imagejpeg ($thumbResource, $this->getImagePath("thumb"), 85);
break;
case IMAGETYPE_PNG:
imagepng ($thumbResource, $this->getImagePath("thumb"));
break;
default:
trigger_error ("Document::storeUploadedImage(): Unhandled or unknown image type ($imageType)", E_USER_ERROR);
}
$this->update();
}
}
// Funcion To Get The Relative Path To The Article's Fullsize Image
public function getImagePath($type="fullsize") {
return ($this->id && $this->imgExtension) ? ("/images" . "/$type/" . $this->id . $this->imgExtension) : false;
}
这是表单输入字段:
<input type="file" name="image" id="image" placeholder="Choose an image to upload" maxlength="255"/>
其余输入存储到 MySQL 数据库表中。上传时没有显示错误。图像未上传到此脚本所需的配置文件中定义的指定目录
最佳答案
不幸的是,我还不能发表评论,所以我写这个作为答案。
您检查图像是否正确上传并使用它,但该函数不执行任何其他操作。然后,您使用 is_uploaded_file
检查文件是否已正确上传,如果没有...您继续您的例程。抛出异常会更明智,就像您在其他地方所做的那样。
您是否将错误报告级别设置为合理的级别(以便您知道出了什么问题)?
关于PHP图像上传并将图像名称存储到MySQL表列脚本不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31424012/