我需要在表格和文件夹中上传图片。请帮助我,我将如何将图像保存在文件夹和数据库中。请描述一下方法。
由于 和Manish
答案 0 :(得分:2)
你可以在PHP中“像往常一样”。我几天前刚刚这样做过:
$path = "/img/avatars/";
$dir = getcwd().$path;
$avatarFile = "$dir$id.png";
if (isset($this->data['User']['avatar']) && $this->data['User']['avatar']['error'] == 0) {
$avatar = $this->data['User']['avatar'];
if (!is_uploaded_file($avatar['tmp_name'])) $this->Utils->panic($avatar);
if (in_array($avatar['type'], array('image/jpeg','image/pjpeg','image/png'))) {
// load image
list($width, $height) = getimagesize($avatar['tmp_name']);
$width = $height = min($width, $height);
if (in_array($avatar['type'], array('image/jpeg','image/pjpeg')))
$source = imagecreatefromjpeg($avatar['tmp_name']);
else
$source = imagecreatefrompng($avatar['tmp_name']);
// resize
$thumb = imagecreatetruecolor(128, 128);
imagecopyresized($thumb, $source, 0, 0, 0, 0, 128, 128, $width, $height);
// save resized & unlink upload
imagepng($thumb, $avatarFile);
$success &= true;
} else {
$this->User->invalidate('avatar', __("Only JPG or PNG accepted.",true));
$success &= false;
}
unlink($avatar['tmp_name']); // Delete upload in any case
}
它甚至会为你调整128x128的大小,你可以跳过它,只需将上传的图像重命名为目标目录。谷歌也会帮助你,文件上传没有特定的蛋糕。
上传表单:
echo $form->create('User', array(
'enctype' => 'multipart/form-data',
'type' => 'post',
));
echo $form->input('avatar', array('type' => 'file', 'label' => __('Avatar:',true)));