how to save image in cakephp
I need to upload image开发者_如何学编程 in table as well as in folder.please help me ,how i will save image in folder and database. please describe the method.
Thanks Manish
You can do it "as usual" in PHP. I just did it a few days ago like this:
$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
}
It's even going to resize it for you always to 128x128, you can skip that and just rename the uploaded image to the target dir. Google will also help you out, there is nothing Cake specific for file uploads.
The uploading form:
echo $form->create('User', array(
'enctype' => 'multipart/form-data',
'type' => 'post',
));
echo $form->input('avatar', array('type' => 'file', 'label' => __('Avatar:',true)));
精彩评论