tags:

views:

26

answers:

1

Hi sir,

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

+1  A: 

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)));
sibidiba
Additional info: mostly uploaded files are stored in the file system, and a reference to it (filename) in the DB. Do not store files in the DB. In my case I did not store anything in the DB, because each user can have only a single avatar, so I just overwrite the existing file, no reference in the DB required.
sibidiba
Thanks for your warm reply.......i want to upload image in folder not in database.if you have code please help me ,currently i m using 1.3 version of cakephpThanks
manish