2015-04-15 15 views
9

Ich möchte Bilder in meine CakePHP 3.0 App hochladen. Aber ich bekomme die Fehlermeldung:cakePHP 3.0 Bilder hochladen

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

Gibt es bereits einige Beispiele für 3.0-Dateien (mehrere Dateien auf einmal) in CakePHP hochladen? Weil ich nur Beispiele für cakePHP 2.x finde!

Ich denke, ich muss eine benutzerdefinierte Überprüfungsmethode in meiner ImagesTable.php hinzufügen? Aber ich kann es nicht zur Arbeit bringen.

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']); 
    } 

Bild add.ctp

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

Bild Entity

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

Antwort

4

Vielleicht folgenden helfen würde. Es ist ein Verhalten, das Ihnen hilft, Dateien sehr einfach hochzuladen!

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

Lassen Sie mich wissen, wenn Sie kämpfen.

Greetz

+0

Hey Mann, bitte helfen? Ich habe die oben installiert, genau das getan, was es in der Dokumentation sagt, aber es ist keine Dateien oder Speicher von Dateinamen in die DB hochladen. Irgendwelche Ideen? – Deej

+0

Bitte setzen Sie sich über gitter.im/bobmulder in Kontakt und einige Code teilen .... – Bob

+0

@SyamsoulAzrien Sie eine neue Frage stellen sollten :-) – Spriz

0

Nun, da jeder hier Werbung für seine Plugins macht, lassen Sie mich dies auch tun. Ich habe das Uploadable-Verhalten in der anderen Frage überprüft, es ist ziemlich einfach und halb fertig, scheint es.

Wenn Sie eine komplette Lösung benötigen, die auf Unternehmensebene skaliert wird, überprüfen Sie FileStorage heraus. Es hat einige Funktionen, die ich noch in keiner anderen Implementierungen gesehen habe, wie zum Beispiel, dass man darauf achtet, dass es nicht zu Dateisystemeinschränkungen kommt, wenn man wirklich viele Dateien bekommt. Es arbeitet zusammen mit Imagine, um die Bilder zu verarbeiten. Sie können jedes einzeln oder in Kombination verwenden, dies folgt SoC.

Es ist vollständig ereignisbasiert, Sie können alles ändern, indem Sie Ihre eigenen Ereignis-Listener implementieren. Es wird einige fortgeschrittene Erfahrungen mit CakePHP erfordern.

Es gibt eine quick start guide zu sehen, wie einfach es ist, es zu implementieren. Der folgende Code stammt von ihm, es ist ein komplettes Beispiel, bitte sehen Sie sich die Kurzanleitung an, die detaillierter ist.

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

Ihrer Ansicht Datei, wie folgt hinzufügen, in meinem Fall Benutzer/Armaturenbrett.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> 

In Ihrem Controller wie folgt hinzufügen, In meinem Fall 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.'); 
    } 
} 

Vor diesem verwenden, erstellen Sie einen Ordner in Webroot namens upload/avatar.

Hinweis: Der Eingang ('Name Here') wird in

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

verwenden Sie es drucken können, wenn Sie das Array Ergebnis sehen wollen.

Das wirkt wie ein Zauber in CakePHP 3.x

+0

Geck habe ich versucht, den Code und das Hochladen Bild funktionierte sehr gut. Aber das Problem ist, dass keine anderen Felddaten jetzt gespeichert werden. Wieso ist es so?? Muss ich irgendwelche Änderungen vornehmen, um das richtige Speichern zu gewährleisten? –

+0

$ this-> request-> Daten sollten zurückkehren, Namen 'Formulardaten als in dem Spaltennamen für die Ex: E-Mail in Tabellennamen in dem E-Mail-Textfeld sein sollte. Der Rest funktioniert genauso. Keine Änderungen erforderlich. –

+0

@PrassannaD failed to open stream: No such file or directory move_uploaded_file() [function.move-uploaded-file]: Kann nicht –

0

Wir https://github.com/josegonzalez/cakephp-upload mit großem Erfolg in der Produktion App, und das seit geraumer Zeit getan.

Hat fantastische Unterstützung für die Verwendung von "Flysystem" (https://flysystem.thephpleague.com/) auch - das ist Abstraktionen von bestimmten Dateisystem (n) - so von normalen lokalen Dateisystem zu S3 ist ein Kinderspiel, oder Dropbox oder was auch immer Sie wollen :-)

Sie können verwandte (qualitativ hochwertige) Plugins zum Hochladen von Dateien finden Sie hier: https://github.com/FriendsOfCake/awesome-cakephp#files - Ich habe "Proffer" mit Erfolg auch verwendet, und es ist keineswegs "fast fertig" oder ähnliches - Beide haben alle meine Empfehlungen und sind in meinen Augen produktionsreif!