2014-10-07 43 views
-2

我試圖上載使用CakePHP圖像,我得到以下錯誤:陣列串錯誤而上傳圖片

通知(8):Array對字符串的轉換[CORE \蛋糕\模型\數據源\ DboSource。 php,line 1009]

<?php echo $this->Form->create('User',array('type'=>'file')); 
     echo $this->Form->input('profile_pic', array('type'=>'file')); 
     echo $this->Form->end('submit'); 
?> 

我做了什麼不對?

回答

0

你研究的CakePHP手冊妥善如何形成的類型可以是文件?????? :)

使用此

<?php echo $this->Form->create('User',array('enctype'=>'multipart/form-data')); 
     echo $this->Form->input('profile_pic', array('type'=>'file')); 
     echo $this->Form->end('submit'); 
?> 
+0

感謝,但仍得到一個錯誤: 無法確定MIME類型。 – Exchanger13 2014-10-08 08:15:05

+0

這就是爲什麼我把它設置爲文件類型,閱讀評論: http://stackoverflow.com/questions/20770144/cakephp-image-can-not-determine-the-mimetype – Exchanger13 2014-10-08 08:17:46

+0

您的項目是否與上述代碼一起工作? – 2014-10-08 08:37:08

0

您需要處理控制器中的文件上傳。如果調試請求你會看到profile_pic領域是一個數組:

# in controller: 
if ($this->request->is('post')) { 
      debug($this->request->data); die(); 
     } 

# result: 
array(
    'User' => array(
     'profile_pic' => array(
      'name' => 'wappy500x500.jpg', 
      'type' => 'image/jpeg', 
      'tmp_name' => '/tmp/phptk28hE', 
      'error' => (int) 0, 
      'size' => (int) 238264 
     ) 
    ) 
) 

簡短的回答:

public function upload() { 
     if ($this->request->is('post')) { 
      if(isset($this->request->data['User']['profile_pic']['error']) && $this->request->data['User']['profile_pic']['error'] === 0) { 
       $source = $this->request->data['User']['profile_pic']['tmp_name']; // Source 
       $dest = ROOT . DS . 'app' . DS . 'webroot' . DS . 'uploads' . DS; // Destination 
       move_uploaded_file($source, $dest.'your-file-name.jpg'); // Move from source to destination (you need write permissions in that dir) 
       $this->request->data['User']['profile_pic'] = 'your-file-name.jpg'; // Replace the array with a string in order to save it in the DB 
       $this->User->create(); // We have a new entry 
       $this->User->save($this->request->data); // Save the request 
       $this->Session->setFlash(__('The user has been saved.')); // Send a success flash message 
      } else { 
       $this->Session->setFlash(__('The user could not be saved. Please, try again.')); 
      } 

     } 
    } 

當然,你需要在上傳文件的額外驗證。

延伸閱讀:https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=site:stackoverflow.com+cakephp+upload+file