Rapid Application Development with Open Source Software

Next: Building Feedback Functionality UP: TOC

We need images in our books. This chapter explains how to develop functionality to upload images.

First we start creating the model

vi /usr/local/www/logikfabrik.com/cakephp/app/Model/Image.php

The content of Image.php is as follows:

 array(
            'className' => 'Book',
            'foreignKey' => 'book_id'
        ),
       'Uploader' => array(
            'className' => 'User',
            'foreignKey' => 'user_id'
        )
    );
}

Once our Model "Image" is ready we need to add the upload functionality in a new controller called "ImagesController.php".

vi /usr/local/www/logikfabrik.com/cakephp/app/Controller/ImagesController.php

The file ImagesController.php has this content:

Session = $this->Components->load('Session'); 
   $this->set('title_for_layout','Image upload');
   Configure::write('Config.language',$this->Session->read('lang'));
   if (!empty($this->request->data)) {
      $this->log('ImagesController:upload step1: ' . print_r($this->request->data,true));
      if ($this->data['Image']['copyright'] == 0) {
         $this->Image->invalidate('copyright', __('Sorry, image not uploaded due to possible copyright violation')); 
      } elseif (is_uploaded_file($this->request->data['Image']['File']['tmp_name']) && 
         $this->request->data['Image']['File']['error'] == 0) {
         $this->Image->create();

         $this->request->data['Image']['image_title'] = trim($this->request->data['Image']['image_title']);
         if (empty($this->request->data['Image']['image_title']))
            $this->request->data['Image']['image_title'] = $this->request->data['Image']['File']['name'];
         if (strlen($this->request->data['Image']['image_title']) > 36)
            $this->request->data['Image']['image_title'] = substr($this->request->data['Image']['image_title'],0,36);
         $this->request->data['Image']['image_type'] = $this->request->data['Image']['File']['type'];
         $this->request->data['Image']['image_filesize'] = $this->request->data['Image']['File']['size'];

         if ($this->request->data['Image']['File']['type'] == 'image/png') $ending = '.png';
         else $ending = '.jpg';

         $this->request->data['Image']['image_internal_filename'] = String::uuid() . $ending;
         $this->request->data['Image']['image_filename'] = $this->request->data['Image']['File']['name'];
         if (strlen($this->request->data['Image']['image_filename']) > 40)
            $this->request->data['Image']['image_filename'] = substr($this->request->data['Image']['image_filename'],0,40);

         $v_destination = ROOT . DS . 'app' . DS. 'webroot' . DS . 'simg' . DS . 
               $this->request->data['Image']['image_internal_filename'];
         $v_source = $this->request->data['Image']['File']['tmp_name'];

         $this->log('ImagesController:upload:  sourcefile:' . $v_source . ' destination:' . $v_destination);

         move_uploaded_file($v_source, $v_destination) or 
           die("
Das File konnte auf dem Server nicht verarbeitet werden."); chmod($v_destination, 0644); $hw = getimagesize($v_destination); $this->log('Image::add step2: ' . print_r($hw,true)); if ($hw[1] > 1200) { //hw[1] = height; hw[0] = width $new_width = 1200; $new_height = floor(1200 / $hw[0] * $hw[1]); $this->log('newheigth: ' . $new_height . print_r($hw,true)); if ($hw[2] == 2) { // JPG $this->log('hw is 2: '); ini_set('memory_limit', '64M'); $newfile = imagecreatetruecolor($new_width,$new_height); $this->log('newfile: ' . $newfile . ' ' . $new_height . ' ' . $new_width); $srcfile = imagecreatefromjpeg($v_destination); $this->log('srcfile: ' . $srcfile); if ($srcfile) { $rc = imagecopyresampled($newfile, $srcfile, 0, 0, 0, 0, $new_width, $new_height, imagesx($srcfile), imagesy($srcfile)); $this->log('imagecopyresampled rc: ' . $rc); imagedestroy($srcfile); $rc = imagejpeg ( $newfile, $v_destination); $this->log('imagejpeg rc: ' . $rc); $this->request->data['Image']['image_height'] = $new_height; $this->request->data['Image']['image_width'] = $new_width; } } } else { $this->request->data['Image']['image_height'] = $hw[1]; $this->request->data['Image']['image_width'] = $hw[0]; } $this->request->data['Image']['image_filesize'] = filesize ( $v_destination ); $this->Image->set($this->request->data); if ($this->Image->validates()) { $this->Image->save($this->data); $this->Session->setFlash(__("Image uploaded",true).': '.$this->request->data['Image']['File']['name'],'axinfo'); $this->redirect('/admin/items'); } else { $errors = $this->Image->invalidFields(); $this->log('ImagesController:upload: Errors after validation: ' . print_r($this->request->data['Image'],true)); $this->log('ImgagesController:upload: Errors:' . print_r($errors,true)); $this->Session->setFlash(implode(',', $errors),'axerror'); } } else { $this->Session->setFlash(__("Error: File not uploaded.",true),'axerror'); $this->log('file not uploaded'); } } } } ?>

Lastly we create the view for the image upload.

vi  /usr/local/www/logikfabrik.com/cakephp/app/View/Images/admin_upload.ctp
Form->create('Image', array('inputDefaults' => array('div' => 'form-group','label' => false, 'wrapInput' => false, 'class' => 'form-control'), 'class' => 'well', 'url' => '/admin/images/add', 'type' => 'file' ) ); echo $this->Form->file('File',array('label'=> __('File',true) )); echo $this->Form->input('image_title',array( 'placeholder' => __('Title of the Image'), 'required' => true ) ); echo $this->Form->input('image_description',array( 'placeholder' => __('Description of the Image'), 'required' => true ) ); echo $this->Form->input('copyright',array( 'type' => 'checkbox', 'label'=> __('I declare that this image is free of any copyright',true), 'class' => false, 'afterx'=> '' . __('Must be declared',true) . '' ) ); echo $this->Form->button(__('Add Image',true), array('type'=>'submit','escape'=>true,'class' => 'btn btn-primary')); echo $this->Form->end(); ?>
Next: Building Feedback Functionality UP: TOC