Thursday, February 14, 2013

Upload single image or file using Cakephp 1.3

This tutorial for upload image or file using Cakephp 1.3.

Step 1 : Create table name 'uploads'

CREATE TABLE `uploads` (
 `id` CHAR(36) NOT NULL PRIMARY KEY,
 `title` VARCHAR(45) NOT NULL,
 `description` TEXT,
 `filename` VARCHAR(255) NOT NULL,
 `filesize` INT(11) UNSIGNED NOT NULL DEFAULT 0,
 `filemime` VARCHAR(45) NOT NULL DEFAULT 'text/plain',
 `created` DATETIME,
 `modified` DATETIME
);

Step 2 : Create view for 'uploads'
path : /views/uploads/add.ctp

<?php echo $this->Form->create(‘Upload’, array(‘type’ => ‘file’));?>
  <fieldset>
     <legend><?php __(‘Add Upload’); ?></legend>
  <?php
  echo $this->Form->input(‘title’);
  echo $this->Form->input(‘description’);
  echo $this->Form->input(‘file’, array(‘type’ => ‘file’));
  ?>
  </fieldset>
<?php echo $this->Form->end(__(‘Submit’, true));?>

Step 3 : Create controller 'uploads_controller'
path : /controllers/uploads_controller.php

Step 3.1 : create function add()

function add() {
  if (!empty($this->data)) {
   $this->Upload->create();
            if ($this->uploadFile() && $this->Upload->save($this->data)) 
{
                $this->Session->setFlash(__('The upload has been saved', true));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The upload could not be saved. Please, try again.', true));
            }
        }
    }


Step 3.2 :create function uploadFile()
path : /webroot/uploads
make sure create folder 'upload' in webroot and permission access to this folder


function uploadFile() {
  $file = $this->data[‘Upload’][‘file’];
  if ($file[‘error’] === UPLOAD_ERR_OK) {
    $id = String::uuid();
    if (move_uploaded_file($file[‘tmp_name’], APP.’webroot/uploads’.DS.$id)) {
      $this->data[‘Upload’][‘id’] = $id;
      $this->data[‘Upload’][‘filename’] = $file[‘name’];
      $this->data[‘Upload’][‘filesize’] = $file[‘size’];
      $this->data[‘Upload’][‘filemime’] = $file[‘type’];
      return true;
    }
  }
  return false;
}

Step 4 : Create view and function for download

i. create view index.ctp
path : /views/uploads/index.ctp

<h2><?php __('Upload'); ?></h2>
<table cellpadding="0" cellspacing="0">
    <tr>
        <th><?php __('id'); ?></th>
        <th><?php __('title'); ?></th>
        <th><?php __('download'); ?></th>
    </tr>
    <?php foreach ($uploads as $upload): ?>
        <tr>
            <td><?php echo $upload['Upload']['id']; ?>&nbsp;</td>
            <td><?php echo $upload['Upload']['title']; ?>&nbsp;</td>
            <td>
                <?php
                echo $this->Html->link(__('Download', true), array(
                    'action' => 'download', $upload['Upload']['id']));
                ?>&nbsp;</td>
        </tr>
    <?php endforeach; ?>
</table>
 
ii. create function download in uploads_controller.php

 
function download($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid id for upload', true));
            $this->redirect(array('action' => 'index'));
        }
        $upload = $this->Upload->find('first', array(
            'conditions' => array(
                'Upload.id' => $id,
            )
                ));
        if (!$upload) {
            $this->Session->setFlash(__('Invalid id for upload', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->view = 'media';
        $filename = $upload['Upload']['filename'];
        $this->set(array(
            'id' => $upload['Upload']['id'],
            'name' => substr($filename, 0, strrpos($filename, '.')),
            'extension' => substr(strrchr($filename, '.'), 1),
            'path' => APP . 'webroot/uploads' . DS,
            'download' => true,
        ));
    }

Extra : Show image in view.ctp
path : /views/uploads/view.ctp

$id = $upload['Upload']['id'];
echo '<img src="'.$this->Html->url(array('controller' => 'uploads','action' => 'download',$id)).'"/>'; 

13 comments:

  1. how to replace an existing image with new image using edit form in cakephp

    ReplyDelete
  2. wheres the model for your database there? do i need it or not anymore? thanks

    ReplyDelete
    Replies
    1. You can used any model where needed for upload file. in this article I used model Upload and Table uploads. If you want to special table for save all uploaded image/file, use another tables. Example,
      Model Post HasMany Album
      Model Album BelongsTo Post

      Delete
    2. http://book.cakephp.org/2.0/en/models/saving-your-data.html#saving-related-model-data-hasone-hasmany-belongsto

      Delete
  3. hi... how about the function index?

    ReplyDelete
  4. hello, can you add restrictions to the file upload?

    ReplyDelete
    Replies
    1. if(($this->data['Upload']['file']['type']== 'image/jpeg' ||
      $this->data['Upload']['file']['type']== 'image/jpg' ||
      $this->data['Upload']['file']['type']== 'image/png') &&
      $this->data['Upload']['file']['size']< 3620888)
      you can add restriction like the code given above.

      Delete
  5. for file extension
    public $validate = array(
    'file' => array(
    'rule' => array(
    'extension',
    array('gif', 'jpeg', 'png', 'jpg')
    ),
    'message' => 'Please supply a valid image.'
    )
    );

    ReplyDelete
  6. for fileSize
    public $validate = array(
    'file' => array(
    'rule' => array('fileSize', '<=', '1MB'),
    'message' => 'Image must be less than 1MB'
    )
    );

    ReplyDelete
  7. can someone tell me that how can i make image upload form where id fetch from cache.

    ReplyDelete
  8. can you tell me how a user login with(fb,gmail) social site network in cakephp 3.2 And How a user login with remember me function?And How we add a captcha in cakephp 3.2?please tell me i am new in cakephp3.please help me here

    ReplyDelete
  9. $file[‘error’] this code gives me an array offset error

    ReplyDelete
  10. $file[‘error’] this code gives me an array offset error

    ReplyDelete