2015-04-15 74 views
9

我想在我的cakephp 3.0應用中上傳圖片。但我收到錯誤消息:cakePHP 3.0上傳圖片

Notice (8): Undefined index: Images [APP/Controller/ImagesController.php, line 55] 

在cakePHP 3.0中是否已經有一些上傳文件(多個文件)的例子?因爲我只能找到CakePHP 2.x的示例!

我想我需要在我的ImagesTable.php中添加自定義驗證方法?但我無法讓它工作。

ImagesTable

public function initialize(array $config) { 
    $validator 
     ->requirePresence('image_path', 'create') 
     ->notEmpty('image_path') 
     ->add('processImageUpload', 'custom', [ 
      'rule' => 'processImageUpload' 
     ]) 
} 

public function processImageUpload($check = array()) { 
    if(!is_uploaded_file($check['image_path']['tmp_name'])){ 
     return FALSE; 
    } 
    if (!move_uploaded_file($check['image_path']['tmp_name'], WWW_ROOT . 'img' . DS . 'images' . DS . $check['image_path']['name'])){ 
     return FALSE; 
    } 
    $this->data[$this->alias]['image_path'] = 'images' . DS . $check['image_path']['name']; 
    return TRUE; 
} 

ImagesController

public function add() 
    { 
     $image = $this->Images->newEntity(); 
     if ($this->request->is('post')) { 
      $image = $this->Images->patchEntity($image, $this->request->data); 

      $data = $this->request->data['Images']; 
      //var_dump($this->request->data); 
      if(!$data['image_path']['name']){ 
       unset($data['image_path']); 
      } 

      // var_dump($this->request->data); 
      if ($this->Images->save($image)) { 
       $this->Flash->success('The image has been saved.'); 
       return $this->redirect(['action' => 'index']); 
      } else { 
       $this->Flash->error('The image could not be saved. Please, try again.'); 
      } 
     } 
     $images = $this->Images->Images->find('list', ['limit' => 200]); 
     $projects = $this->Images->Projects->find('list', ['limit' => 200]); 
     $this->set(compact('image', 'images', 'projects')); 
     $this->set('_serialize', ['image']); 
    } 

圖片add.ctp

<?php 
    echo $this->Form->input('image_path', [ 
     'label' => 'Image', 
     'type' => 'file' 
     ] 
    ); 
?> 

圖片實體

protected $_accessible = [ 
    'image_path' => true, 
]; 

回答

4

也許下面會有所幫助。這是一種能夠幫助您上傳文件的行爲!

http://cakemanager.org/docs/utils/1.0/behaviors/uploadable/

讓你奮鬥我知道。

格爾茨

+0

嘿,請幫忙嗎?我已經安裝了上述內容,完全按照文檔中的說法進行,但不會上傳文件或將文件名存儲到數據庫。有任何想法嗎? – Deej

+0

請通過gitter.im/bobmulder與我聯繫,並分享一些代碼.... – Bob

+0

@SyamsoulAzrien你應該問一個新問題:-) – Spriz

0

現在,每個人都做的廣告,他在這裏的插件,讓我做這一點。我已經檢查了另一個問題中的可上傳行爲,這很簡單,看起來似乎有一半。

如果你想要一個完整的解決方案,在企業級上進行擴展,請檢查FileStorage。它具有我在其他任何實現中沒有看到的一些功能,但是在確保您的文件系統不會受到文件系統限制的情況下,您可以獲得真的許多文件。它與Imagine一起處理圖像。你可以單獨使用或者組合使用,這個如下SoC

它完全基於事件,您可以通過實現您自己的事件偵聽器來更改所有內容。它需要CakePHP的一些中級水平的經驗。

有一個quick start guide看到它是多麼容易實現它。下面的代碼是從中獲取的,這是一個完整的例子,請參閱快速入門指南,它更詳細。

class Products extends Table { 
    public function initialize() { 
     parent::initialize(); 
     $this->hasMany('Images', [ 
      'className' => 'ProductImages', 
      'foreignKey' => 'foreign_key', 
      'conditions' => [ 
       'Documents.model' => 'ProductImage' 
      ] 
     ]); 
     $this->hasMany('Documents', [ 
      'className' => 'FileStorage.FileStorage', 
      'foreignKey' => 'foreign_key', 
      'conditions' => [ 
       'Documents.model' => 'ProductDocument' 
      ] 
     ]); 
    } 
} 

class ProductsController extends ApController { 
    // Upload an image 
    public function upload($productId = null) { 
     if (!$this->request->is('get')) { 
      if ($this->Products->Images->upload($productId, $this->request->data)) { 
       $this->Session->set(__('Upload successful!'); 
      } 
     } 
    } 
} 

class ProductImagesTable extends ImageStorageTable { 
    public function uploadImage($productId, $data) { 
     $data['adapter'] = 'Local'; 
     $data['model'] = 'ProductImage', 
     $data['foreign_key'] = $productId; 
     $entity = $this->newEntity($data); 
     return $this->save($data); 
    } 
    public function uploadDocument($productId, $data) { 
     $data['adapter'] = 'Local'; 
     $data['model'] = 'ProductDocument', 
     $data['foreign_key'] = $productId; 
     $entity = $this->newEntity($data); 
     return $this->save($data); 
    } 
} 
0
/*Path to Images folder*/ 
$dir = WWW_ROOT . 'img' .DS. 'thumbnail'; 
/*Explode the name and ext*/ 
       $f = explode('.',$data['image']['name']); 
       $ext = '.'.end($f); 
    /*Generate a Name in my case i use ID & slug*/ 
       $filename = strtolower($id."-".$slug); 

    /*Associate the name to the extension */ 
       $image = $filename.$ext; 


/*Initialize you object and update you table in my case videos*/ 
       $Videos->image = $image;  
      if ($this->Videos->save($Videos)) { 
/*Save image in the thumbnail folders and replace if exist */ 
      move_uploaded_file($data['image']['tmp_name'],$dir.DS.$filename.'_o'.$ext); 

      unlink($dir.DS.$filename.'_o'.$ext); 
       } 
0
<?php 
namespace App\Controller\Component; 

use Cake\Controller\Component; 
use Cake\Controller\ComponentRegistry; 
use Cake\Network\Exception\InternalErrorException; 
use Cake\Utility\Text; 

/** 
* Upload component 
*/ 
class UploadRegCompanyComponent extends Component 
{ 

    public $max_files = 1; 


    public function send($data) 
    { 
     if (!empty($data)) 
     { 
      if (count($data) > $this->max_files) 
      { 
       throw new InternalErrorException("Error Processing Request. Max number files accepted is {$this->max_files}", 1); 
      } 

      foreach ($data as $file) 
      { 
       $filename = $file['name']; 
       $file_tmp_name = $file['tmp_name']; 
       $dir = WWW_ROOT.'img'.DS.'uploads/reg_companies'; 
       $allowed = array('png', 'jpg', 'jpeg'); 
       if (!in_array(substr(strrchr($filename , '.') , 1) , $allowed)) 
       { 
        throw new InternalErrorException("Error Processing Request.", 1);  
       } 
       elseif(is_uploaded_file($file_tmp_name)) 
       { 
        move_uploaded_file($file_tmp_name, $dir.DS.Text::uuid().'-'.$filename); 
       } 
      } 
     } 
    } 
} 
9

在你的視圖文件,加入這樣的,在我的情況用戶/儀表板。CTP

<div class="ChImg"> 
<?php 
echo $this->Form->create($particularRecord, ['enctype' => 'multipart/form-data']); 
echo $this->Form->input('upload', ['type' => 'file']); 
echo $this->Form->button('Update Details', ['class' => 'btn btn-lg btn-success1 btn-block padding-t-b-15']); 
echo $this->Form->end();  
?> 
</div> 

在您的控制器添加這樣的,在我的情況UsersController

if (!empty($this->request->data)) { 
if (!empty($this->request->data['upload']['name'])) { 
$file = $this->request->data['upload']; //put the data into a var for easy use 

$ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension 
$arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions 
$setNewFileName = time() . "_" . rand(000000, 999999); 

//only process if the extension is valid 
if (in_array($ext, $arr_ext)) { 
    //do the actual uploading of the file. First arg is the tmp name, second arg is 
    //where we are putting it 
    move_uploaded_file($file['tmp_name'], WWW_ROOT . '/upload/avatar/' . $setNewFileName . '.' . $ext); 

    //prepare the filename for database entry 
    $imageFileName = $setNewFileName . '.' . $ext; 
    } 
} 

$getFormvalue = $this->Users->patchEntity($particularRecord, $this->request->data); 

if (!empty($this->request->data['upload']['name'])) { 
      $getFormvalue->avatar = $imageFileName; 
} 


if ($this->Users->save($getFormvalue)) { 
    $this->Flash->success('Your profile has been sucessfully updated.'); 
    return $this->redirect(['controller' => 'Users', 'action' => 'dashboard']); 
    } else { 
    $this->Flash->error('Records not be saved. Please, try again.'); 
    } 
} 

使用此之前,Webroot公司命名上傳/化身創建一個文件夾。

注:輸入('名稱這裏),用於在

$this->request->data['upload']['name'] 

您可以打印,如果你想看到的數組結果。

它的工作原理是在CakePHP的3.X

+0

老兄我試着你的代碼和圖像上傳工作得很好。但問題是現在沒有其他現場數據得到保存。爲什麼這樣?我是否需要進行任何更改以確保正確保存? –

+0

$ this-> request->數據應該返回表單數據'名稱',如列表名稱中的名稱:表名中的電子郵件應位於電子郵件文本框中。其餘的工作原理相同。無需更改。 –

+0

@PrassannaD無法打開流:無此文件或目錄move_uploaded_file()[function.move-uploaded-file]:無法移動 –

0

魅力,我們使用https://github.com/josegonzalez/cakephp-upload在我們的生產應用大獲成功,並且已經持續了相當一段時間。

對於使用「Flysystem」(https://flysystem.thephpleague.com/)以及特定文件系統的抽象類型也有很好的支持 - 因此,從正常的本地文件系統遷移到S3是一件不容易的事情,或者Dropbox或任何地方想要:-)

你可以在這裏找到相關的(高質量)插件文件上傳:https://github.com/FriendsOfCake/awesome-cakephp#files - 我已經用「Proffer」成功了,它絕不是「幾乎完成」或任何類似的東西 - 都有我的建議,並在我眼中的生產準備!