2014-02-26 46 views
-1

我一直在試圖上傳一個圖像文件到我的數據庫中,作爲屬性image_name。我希望能夠存儲圖像,然後它的文件路徑保存到我的數據庫..香港專業教育學院嘗試了這裏的許多選項..但似乎無法弄清楚如何做到這一點...Yii將圖像上傳到數據庫

這是什麼我走到這一步,如果有人可以點我這將是偉大正確的方向...

感謝

型號 -

public function attributeLabels() 
{ 
    return array(
     'id' => 'ID', 
     'movie_name' => 'Movie Name', 
     'studio_id' => 'Studio', 
     'country_id' => 'Country', 
     'movie_rating_id' => 'Movie Rating', 
     'map_pin_id' => 'Map Pin', 
     'description' => 'Description', 
     'title_image' => 'Title Image', 
     'title_trailer_youtube_code' => 'Title Trailer Youtube Code', 
     'release_date' => 'Release Date', 
     'bg_colour_code' => 'Bg Colour Code', 
     'text_colour_code' => 'Text Colour Code', 
     'is_released' => 'Is Released', 
     'is_advanced_booking_allowed' => 'Is Advanced Booking Allowed', 
     'advanced_booking_start_date' => 'Advanced Booking Start Date', 
     'advanced_booking_end_date' => 'Advanced Booking End Date', 
     'domain_prefix' => 'Domain Prefix', 
     'facebook_app_id' => 'Facebook App', 
     'facebook_app_url' => 'Facebook App Url', 
     'facebook_icon_image_url' => 'Facebook Icon Image Url', 
     'facebook_text' => 'Facebook Text', 
     'twitter_text' => 'Twitter Text', 
     'booking_share_text' => 'Booking Share Text', 
     'home_tracking_url' => 'Home Tracking Url', 
     'shows_tracking_url' => 'Shows Tracking Url', 
    ); 
} 

控制器 -

public function actionCreate() 
{ 
    $model=new Movie; 

    // Uncomment the following line if AJAX validation is needed 
    // $this->performAjaxValidation($model); 

    if(isset($_POST['Movie'])) 
    { 
     $model->attributes=$_POST['Movie']; 
     $uploadedFile=CUploadedFile::getInstance($model,'title_image'); 
     $fileName = $uploadedFile; 
     $model->title_image = $fileName; 
     if($model->save()) 
      $uploadedFile->saveAs('http://localhost:8888/MY/Movies/title_image/'.$fileName); 
      $this->redirect(array('view','id'=>$model->id)); 
    } 

    $this->render('create',array(
     'model'=>$model, 
    )); 
} 
+0

你的問題根本沒有提供任何信息。問題是什麼?怎麼了? – Jon

+0

它似乎並沒有在數據庫中創建新記錄,也沒有將圖像文件路徑或圖像存儲在其位置中。 – user3355603

+0

閱讀[documentation](http://www.yiiframework.com/doc/api /1.1/CUploadedFile)可能會有所幫助:「調用'getInstance'來檢索上傳文件的實例,然後使用'saveAs'將其保存在服務器上。」 – Jon

回答

0

閱讀你的代碼,uploadedFile->saveAs()方法期望的文件,而不是URL完整路徑。

要獲得完整的路徑,嘗試這樣的:

$uploadedFile->saveAs(Yii::getPathOfAlias('webroot').'/images/uploaded/'.$fileName); 

在這個例子中images目錄應該在同一水平protected目錄(僅在用於顯示的公衆形象通過URL images DIR):

assets/ 
images/ 
protected/ 
themes/ 

如果您在Unix環境下,請確保對images dir進行正確的讀/寫訪問。

如果還不行,review this useful sample tutorial step by step,有助於引進到文件與誼上傳。

+0

感謝您指引我在正確的方向 – user3355603