2017-05-31 63 views
0

我試圖將圖像上傳到我的本地文件夾CakePHP的2X上傳圖像

根目錄/ IMG/

和圖像名稱保存到數據庫中。一切似乎都工作正常,但圖像沒有保存到路徑

這是我的看法

<?php echo $this->Form->create(null,['url' => ['controller' => 'users', action' => 'update_image'], 
array('enctype'=>'multipart/form-data')]); ?> 
<?php echo $this->Form->input('User.id') ?> 
<?php echo $this->Form->file('Profile.picture',['type'=>'file']) ?> 
<?php echo $this->Form->end('submit') ?> 

我控制器

public function update_image(){ 

    $id = $this->Auth->user('id'); 
    $this->Profile->id = $id; 
    $this->set('profile', $this->User->findById($id)); 

    if ($this->request->is(array('post','put'))) { 
    $frmData = $this->request->data; 

     //Path to store upload image 
     $target = "/teamjob_back/img/../img/".basename($frmData['Profile']['picture']); 

     //Get the data from form 
     $image = $frmData['Profile']['picture']; 

     //save data to database 
     $this->Profile->save($this->request->data); 

     //Image store to the img folder 
     if (move_uploaded_file($image['tmp_name']['name'], $target)) { 
      echo "Image successfull"; 
     } 
    } 
} 

和代碼

$image['tmp_name']['name'] 

給了我一個非法串偏移誤差。

EDITED 此代碼工作在控制器上

if ($this->request->is('post')) { 
     $frmData = $this->request->data; 
     $tmp = $frmData['picture']['tmp_name']; 
     $hash = rand(); 
     $date = date("Ymd"); 
     $image = $date.$hash."-".$frmData['picture']['name']; 
     $target = WWW_ROOT.'img'.DS.'uploads'.DS; 

     $target = $target.basename($image); 
     if (move_uploaded_file($tmp, $target)) { 
      echo "Successfully moved"; 
     } 
     else 
     { 
      echo "Error"; 
     } 
    } 
+0

'形式 - >創建(NULL,['加密類型,包括加密類型'=>'multipart/form-data'])?>你在創建表單時是否添加了enctype? –

+0

'

' –

+0

該代碼有效 –

回答

0

首先添加

['type' => 'file'] 

作爲一個選項,您的文件,而不是試圖發送加密類型。

$image$this->request->data['Profile']['picture']所以你不能做['tmp_name']['name']在一起...調試($this->request->data['Profile']['picture'],你會看到,你可以有

$image['tmp_name'] 

$image['name'] 

但不能同時在一起。

可能更多,但這些都是很好的開始。

+0

i在我的控制器上執行了這個'move_uploaded_file($ image ['name'],$ target)'還有'<?php echo $ this-> Form-> create(null,['url'=> ['controller'=> 'user','action'=>'update_image'], array('type'=>'file')]); ?>'對我的看法,但仍然沒有任何反應,你可以指示我更多謝謝你先生 –

+0

,應該沒有工作......你需要$ image ['tmp_name']到目標,因爲它會移動說/ tmp /image.jdkkd.jpeg到目標....然後你想要將它保存到db中 –

+0

你可能會考慮使用像Proffer這樣的東西。 –

0

首先,你需要刪除「型=>文件」監守你已經使用表格幫手「文件」功能,如果我們用「形式 - >輸入」然後我們用「型=>文件」

e.g. $this->Form->input('email', array('type' => 'email')); 
$this->Form->file('Profile.picture') 

檢查你的目標路徑是否有寫權限,pr($ image)然後你得到正確的數組格式$ image ['temp_name]或$ image [0] ['temp_name]等 並把你的temp_name在move_uploaded_file功能

e.g. move_uploaded_file(your temp_name) 

Form Helper

0

確保當您創建的形式上傳文件

<?= $this->Form->create(NULL, ['enctype' => 'multipart/form-data']) ?>