2010-05-20 48 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