单浏览多个图像上传

时间:2014-03-27 14:19:00

标签: cakephp cakephp-2.3

首先,我想尽你所能感谢你们的贡献和帮助。

现在我想问一些事情,也许不是什么大问题,但即使我已经尝试了很多不同的方法,我也找不到解决它的方法。

所以要详细解释..我有一个 typology_pictures 表,它有id | typology_id | pic_path。

当用户想要创建一个新的typology_picture时,它会显示如下:

Adding Images For a chosen Typology

因此,用户选择这些图片所包含的类型,当他眉毛时,我想让他选择多个图像。  当他按下提交时,所有图像都插入数据库中,每个图像都在一个新行中,但 typology_id 是相同的,只是pic_path是不同的。

所以模型是这样的:

<?php
App::uses('AppModel', 'Model');
/**
 * TypologyPicture Model
 *
 * @property Typology $Typology
 */
class TypologyPicture extends AppModel {
public $name = 'TypologyPicture';

    public $primaryKey = 'id';

    public $displayField = 'typology_id';


    public $validate = array(
        'id' => array(
            'blank' => array(
                'rule' => 'blank',
                'on' => 'create',
            ),
        ),
        'typology_id' => array(
            'numeric' => array(
                'rule' => array('numeric'),
                'message' => 'Chose the Typology this pic belongs to?',
            ),
            'notEmpty' => array(
                'rule' => array('notEmpty'),
                'message' => 'Select The typology where these picture belongs to? ',
                'on' => 'create',
            ),
        ),
        'pic_path' => array(
            'uploadError' => array(
                'rule' => 'uploadError',
                'message' => 'The Typology Image upload failed.',
                'allowEmpty'=>false,
                'on' => 'create',
             ),
             'fileSize' => array(
                'rule' => array('fileSize', '<=', '3MB'),
                'message' => 'Cover image must be less than 3MB.',
                'allowEmpty'=>false,
                'on' => 'create',

             ),
            'processTypologyImageUpload' => array(
                'rule' => 'processTypologyImageUpload',
                'message' => 'Unable to process cover image upload.',
                'allowEmpty' => TRUE,
             ),
        ),
    );

    //The Associations below have been created with all possible keys, those that are not needed can be removed

/**
 * belongsTo associations
 *
 * @var array
 */
    public $belongsTo = array(
        'ItemTypologyPicture' => array(
            'className' => 'Typology',
            'foreignKey' => 'typology_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        )
    );


        /*CopyRight @Erland Muchasaj*/
    // This new function Doesent Upload the Picture or Image unless the Record is inserted in DB.
    public function processTypologyImageUpload($checktypology = array()) {  
        $dir = 'img' . DS . 'uploads' . DS . 'typology' . DS . 'images' . DS;
            if (!isset($checktypology['pic_path']['name'])) {
                $this->invalidate('pic_path', 'You must upload a file before you Submit!');  
                return false;
            }

            if(!is_uploaded_file($checktypology['pic_path']['tmp_name'])) {
                $this->invalidate('pic_path', 'You must upload a file before you Submit!'); 
                return false; 
            } 

            if (($checktypology['pic_path']['size'] > 55000000)) {
                $this->invalidate('pic_path', 'File size is To big!');  
                return false; 
            }
                $allowedExts = array('jpeg', 'png', 'jpg', 'gif','tiff');
                $value = explode(".", $checktypology['pic_path']['name']); // Here we grab the name of the file with the extension
                $extension = strtolower(array_pop($value));   //extension
                // the file name is before the last "."
                $fileName = array_shift($value);  //Filename                        
            //$allowedExts = array('jpeg', 'png', 'jpg', 'gif','tiff');
            //$extension=strtolower(end(explode(".", $checktypology['pic_path']['name']))); 
            if(!in_array($extension, $allowedExts)){
                $this->invalidate('pic_path', 'Invalid File Format! '); 
                return false;
            }   

            if ($checktypology['pic_path']["error"] > 0) {   
                $this->invalidate('pic_path', $checktypology['pic_path']['error']);
                return false;  
            }

            if (file_exists( WWW_ROOT . $dir) && is_dir( WWW_ROOT . $dir))  { 
                chmod(WWW_ROOT . $dir, 0777);
                if (file_exists( WWW_ROOT . $dir . $checktypology['pic_path']['name'])) { 
                    $this->invalidate('pic_path', 'File Allredy Exists!');
                    return false;     
                } 
            }

            if (!file_exists( WWW_ROOT . $dir) || !is_dir( WWW_ROOT . $dir))  { 
                mkdir($dir, 0777, true);
            }            
     // better safe then sorry!
     return true; 
    }


    // this is a Global variable that im gonna use it inside my function
        private  $image;
        public function beforeSave($options = Array()) {
            $dir = 'img' . DS . 'uploads' . DS . 'typology' . DS . 'images' . DS;
            // first  we grab slider id, and we pass it's data the the variable.
            $this->image = $this->find('first', array('conditions' => array('TypologyPicture.id' => $this->id)));

                if (isset($this->data[$this->alias]['pic_path']) && !empty($this->data[$this->alias]['pic_path'])) {
                    $file = $this->data[$this->alias]['pic_path'];
                        if (!move_uploaded_file($file['tmp_name'], WWW_ROOT . $dir .  time() .$file['name'])) {
                            $this->invalidate('pic_path', 'File Didnt Upload! ');
                            return FALSE;
                        }
                    $this->data[$this->alias]['pic_path'] = time() . $file['name'];
                return TRUE;
                }       
            return true;
        }

        public function afterSave($created, $options = Array()) {
            //$dir = 'img/uploads/typology/images/'; /*<=== DO NOT EDIT*/
            $dir = 'img' . DS . 'uploads' . DS . 'typology' . DS . 'images' . DS;
            // then after deletation of the row we check if the file exist, if so we delete it. 
            if(isset($this->data[$this->alias]['pic_path']) && file_exists(WWW_ROOT . $dir .  $this->image['TypologyPicture']['pic_path'])){
            chmod(WWW_ROOT . $dir, 0777);
                $img = WWW_ROOT . $dir . $this->image ['TypologyPicture']['pic_path'];
                unlink($img); 
                return true;
           } else { $this->data[$this->alias]['pic_path'] = $this->image['TypologyPicture']['pic_path'];}
           return true;
        }


        // this is a Global variable that im gonna use it inside my function
        private  $TypologyPicture;
        public function beforeDelete($cascade = true) {
            // first  we grab slider id, and we pass it's data the the variable.
            $this->TypologyPicture = $this->find('first', array('conditions' => array('TypologyPicture.id' => $this->id)));
            return true;
        }

         public function afterDelete() {
         //$dir = 'img/uploads/typology/images/'; /*<=== DO NOT EDIT*/
         $dir = 'img' . DS . 'uploads' . DS . 'typology' . DS . 'images' . DS;
         // then after deletation of the row we check if the file exist, if so we delete it. 
            if(file_exists(WWW_ROOT . $dir .  $this->TypologyPicture['TypologyPicture']['pic_path'])){
            chmod(WWW_ROOT . $dir, 0777);
                $img = WWW_ROOT . $dir . $this->TypologyPicture ['TypologyPicture']['pic_path'];
                unlink($img); 
                return true;
           }
           return true;
        } 


}

添加操作的控制器:

public function add() {
    $this->layout='typology_add';
    if ($this->request->is('post')) {       
         if (!empty($this->data)) {

            $this->TypologyPicture->create();
            if(empty($this->data['TypologyPicture']['pic_path']['name'])){
                unset($this->request->data['TypologyPicture']['pic_path']);
              }
            if ($this->TypologyPicture->saveAll($this->data)) 
            {        
                $this->Session->setFlash(__('The profile has been saved', true));
                $this->redirect(array('action' => 'index'));
            } else 
            {
                $this->Session->setFlash(__('The profile could not be saved. Please, try again.', true));
            } // END OF TypologyPicture->save


       } // END OF THE !empty();    
     if (empty($this->data)) {
            $this->data = $this->TypologyPicture->read(null, $id);
        }        
    }


        $typologies = $this->TypologyPicture->ItemTypologyPicture->find('list');
    $this->set(compact('typologies'));
} 

观点如下:

<?php echo $this->Form->create('TypologyPicture', array('type'=>'file')); ?>
    <legend><?php echo __('Add Typology Pictures'); ?></legend>
  <?php
    echo $this->Form->input('id');
    echo $this->Form->input('typology_id');
    echo $this->Form->input('pic_path', array('label'=>'Picture','type'=>'file'));
  ?>
<?php echo $this->Form->end(__('Submit')); ?>

我真的很高兴你的帮助。

感谢名单!

修改

这是我到目前为止编写的代码!

public function add() {
    if ($this->request->is('post')) {       
        $dir = 'img' . DS . 'uploads' . DS . 'typology' . DS . 'images' . DS;
        for($i=0;$i<count($this->request->data['TypologyPicture']['pic_path']['name']);$i++){
            if(empty($this->data['TypologyPicture']['pic_path'][$i]['name'])) {
                unset($this->request->data['TypologyPicture']['pic_path'][$i]['name']);
            }
            if(!empty($this->request->data['TypologyPicture']['pic_path'][$i]['tmp_name'])){    
                $allowedExts = array('jpeg', 'png', 'jpg', 'gif','tiff');
                $value = explode(".", $this->data['TypologyPicture']['pic_path'][$i]['name']); // Here we grab the name of the file with the extension
                $extension = strtolower(array_pop($value));   //extension
                if(in_array($extension, $allowedExts)){
                    if ($this->data['TypologyPicture']['pic_path'][$i]['error'] <= 0) { 
                        chmod(WWW_ROOT . $dir, 0777); 
                        move_uploaded_file($this->data['TypologyPicture']['pic_path'][$i]['tmp_name'], WWW_ROOT . $dir  . mktime().$this->data['TypologyPicture']['pic_path'][$i]['name']);
                        $this->request->data['TypologyPicture']['pic_path'] = mktime().$this->data['TypologyPicture']['pic_path'][$i]['name'];
                    }
                }
            } 
            $this->TypologyPicture->create();
            if ($this->TypologyPicture->save($this->data)){        
                $this->Session->setFlash(__('The profile has been saved', true));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The profile could not be saved. Please, try again.', true));
            } // END OF ItemPicture->save
        }
    }        
    $typologies = $this->TypologyPicture->ItemTypologyPicture->find('list');
    $this->set(compact('typologies'));
}

我还将输入字段更改为:

echo $this->Form->input('pic_path.', array('label'=>'Picture','multiple'=>'multiple' ,'type'=>'file')); 

为了支持多文件选择。但似乎没有什么工作......

我得到一个:

请求已被黑洞错误:在此服务器上找不到请求的地址'/ cesifull / typology_pictures / add'。

任何建议......任何人!

1 个答案:

答案 0 :(得分:0)

能够通过单个文件输入选择多个文件是HTML5功能,因此您编写的任何解决方案都很可能涉及HTML5。如果您不想使用HTML5,那么人们也可以为多个图像上传制作Flash和Java插件。

http://verens.com/2009/12/28/multiple-file-uploads-using-html5/