2010-05-20 50 views

回答

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 
      } 

它甚至会一直调整其大小为您128×128,可以跳过这一点,只是上传的图片重命名为目标目录。谷歌也会帮助你,没有什么特别的文件上传的Cake。

的上传方式:

echo $form->create('User', array(
    'enctype' => 'multipart/form-data', 
    'type' => 'post', 
)); 
echo $form->input('avatar', array('type' => 'file', 'label' => __('Avatar:',true))); 
+0

附加信息:主要是上传的文件都存储在文件系统中,并在DB它(文件名)的参考。不要将文件存储在数据库中。在我的情况下,我没有在数据库中存储任何东西,因为每个用户只能有一个头像,所以我只是覆盖现有的文件,在数据库中不需要引用。 – sibidiba 2010-05-20 11:44:46

+0

感谢您的热情回复....... 我想在文件夹中database.if上传图片您有没有代码,请帮助我,目前I M采用1.3版本的CakePHP 感谢 – manish 2010-05-21 06:55:19

+0

几乎可以复制你的例子。谢谢! – nicojs 2011-07-22 19:01:23