2011-07-12 36 views
1

我最近開始研究zend框架。我想上傳個人資料圖片並將其重命名爲&。我正在使用下面的代碼。有了這個能夠上傳,但不能重新命名,並且沒有辦法重新設置上傳的文件的大小。在zend框架中創建個人照片上傳器

如果($這個 - > Request()方法 - > isPost()){

  if(!$objProfilePictureForm->isValid($_POST)) 
      { 
       //return $this->render('add'); 

      } 

      if(!$objProfilePictureForm->profile_pic->receive()) 
      { 
       $this->view->message = '<div class="popup-warning">Errors Receiving File.</div>'; 


      } 

      if($objProfilePictureForm->profile_pic->isUploaded()) 
      { 
       $values = $objProfilePictureForm->getValues(); 
       $source = $objProfilePictureForm->profile_pic->getFileName(); 


       //to re-name the image, all you need to do is save it with a new name, instead of the name they uploaded it with. Normally, I use the primary key of the database row where I'm storing the name of the image. For example, if it's an image of Person 1, I call it 1.jpg. The important thing is that you make sure the image name will be unique in whatever directory you save it to. 

       $new_image_name = 'new'; 

       //save image to database and filesystem here 
       $image_saved = move_uploaded_file($source, '../uploads/thumb'.$new_image_name); 
       if($image_saved) 
       { 
        $this->view->image = '<img src="../uploads/'.$new_image_name.'" />'; 
        $objProfilePictureForm->reset();//only do this if it saved ok and you want to re-display the fresh empty form 
       } 
      } 
     } 

回答

3

要重命名文件上傳時,你將不得不 「重新命名,過濾器」 添加到您的文件 - 形元件。該課程被稱爲Zend_Filter_File_Rename

// Create the form 
$form = new Zend_Form(); 

// Create an configure the file-element 
$file = new Zend_Form_Element_File('file'); 
$file->setDestination('my/prefered/path/to/the/file') // This is the path where you want to store the uploaded files. 
$file->addFilter('Rename', array('target' => 'my_new_filename.jpg')); // This is for the filename 
$form->addElement($file); 

// Submit-Button 
$form->addElement(new Zend_Form_Element_Submit('save'); 

// Process postdata 
if($this->_request->isPost()) 
{ 
    // Get the file and store it within the specified destination with the specified name. 
    $file->receive(); 
} 

要使文件名動態變化,您可以使用時間戳或其他命名。您也可以在$file->receive()的調用之前在您的數據處理後應用重命名過濾器。如果您向表中插入一行並希望用剛剛插入的行的id命名文件,這可能很有用。

既然你想存儲個人資料圖片,你可以從你的數據庫中獲取用戶的ID並用該ID命名圖片。

+0

thanks faileN!可以üPLZ告訴我我們如何使文件名稱動態,並可以將文件移動到其他位置 – anurodh

+0

我編輯了我的答案。往上看。 –