2011-07-12 7 views
1

最近、zendフレームワークの作業を開始しました。私はプロフィール画像をアップロードして、&の名前を変更し直したいと思います。以下のコードを使用しています。アップロードすることはできますが、名前を変更することはできず、アップロードされたファイルのサイズを変更する方法はありません。zendフレームワークでプロフィール画像アップローダーを作成する

(の$ this - >のGetRequest() - > 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でファイルに名前を付ける場合に便利です。

プロファイル画像を保存したいので、あなたのdbからユーザーのIDを取得し、そのIDで画像に名前を付けることができます。

+0

ありがとうfaileN!どのようにファイル名を動的にすることができ、ファイルを別の場所に移動させることができるのか教えてください。 – anurodh

+0

私は自分の答えを編集しました。上記を参照。 –

関連する問題