In this post I will describe how to upload images in CakePHP. It will automatically upload and move the uploaded file to the wanted location. It will automatically rename the file if there is another file with same name exist. A lot of other features are also available.
- Download Upload Component file and copy it to the location app/Controller/Component/UploadComponent.php
- Initialize
1var $components = array('Upload');
- Your add action would looks like:
123456789101112131415161718192021222324252627282930public function add() {if ($this->request->is('post')) {if (!empty($this->request->data) && is_uploaded_file($this->request->data['Gallery']['image']['tmp_name'])) {$this->Upload->upload($this->data['Gallery']['image']);if ($this->Upload->uploaded) {$this->Upload->file_new_name_body = 'image_resized';$this->Upload->image_resize = true;$this->Upload->image_x = 400;$this->Upload->image_ratio_y = true;$this->Upload->process(Configure::read('UploadPath'));if ($this->Upload->processed) {$this->Upload->clean();$this->request->data['Gallery']['image'] = basename($this->Upload->file_dst_name);} else {$errors = $this->Upload->error;$this->Session->setFlash(__($errors));exit();}}}$this->Gallery->create();if ($this->Gallery->save($this->request->data)) {$this->Session->setFlash(__('The gallery has been saved'));$this->redirect(array('controller' => 'galleries' ,'action' => 'index'));} else {$this->Session->setFlash(__('The gallery could not be saved. Please, try again.'));}}} - We have setup our controller. Now its time to setup view file add.ctp. The file file should look like following:
12345678910111213141516171819<div class="galleries form">< ?php echo $this->Form->create('Gallery', array('enctype' => 'multipart/form-data'));?><fieldset><legend>< ?php echo __('Add Gallery'); ?></legend>< ?phpecho $this->Form->input('caption');echo $this->Form->input('desc');echo $this->Form->file('image');?></fieldset>< ?php echo $this->Form->end(__('Submit'));?></div><div class="actions"><h3>< ?php echo __('Actions'); ?></h3><ul><li>< ?php echo $this->Html->link(__('List Galleries'), array('action' => 'index'));?></li></ul></div>
- All done.
UploadComponent class file is well document so you can always find all configuration setting for the uploaded images.