Subir Imagenes en cakephp 2.6

140 views
Skip to first unread message

Juandy Ocampo

unread,
Jun 22, 2015, 8:26:18 PM6/22/15
to cakep...@googlegroups.com
Hola a todos, quería hacerles una consulta, estoy tratando de subir imagenes para un proyecto que me pidieron, y este es mi código:

public function add() {
        if ($this->request->is('post')) {
            //Subir imagenes
            if ($this->data['Aparato']['id_foto']) {
                $file = new File($this->request->data['Aparato']['id_foto']['tmp_name'], true, 0644);
$path_parts = pathinfo($this->data['Aparato']['id_foto']['name']);
$ext = $path_parts['extension'];
if ($ext != 'jpg' && $ext != 'jpeg' && $ext != 'gif' && $ext != 'png') {
                    $this->Session->setFlash('Solo puedes subir imagenes.');
                    $this->render();
                else {
                    $date = $this->request->data['Aparato']['id_foto']['name'];
                    $filename =$date.'-post-image.'.$ext;
                    $data = $file->read();
                    $file->close();
                    $file = new File(WWW_ROOT.'/img/'.$filename,true);
                    $file->write($data);
                    $file->close();
}
            }
            //Fin subir imagenes
            $this->data['Aparato']['id_foto'] = $this->data['Aparato']['id_foto']['name'];
            $this->Aparato->create();
            if ($this->Aparato->save($this->request->data)) {
                $this->Session->setFlash(__('Aparato Guardado'));
                $this->redirect(array('action' => 'index'));
            } 
            else {
                $this->Session->setFlash(__('error al crear aparato'));
            }    
        }
    }

Por alguna razón no me guarda el aparato en la bd, y me da el sgtes errores:

rror: The application is trying to load a file from the Upload plugin

Error: Make sure your plugin Upload is in the app/Plugin directory and was loaded

<?php
CakePlugin::load('Upload');

Loading all plugins: If you wish to load all plugins at once, use the following line in your app/Config/bootstrap.php file

CakePlugin::loadAll();

Notice: If you want to customize this error message, create app/View/Errors/missing_plugin.ctp


Cómo verán no sé que hacer, cualquier respuesta la agradeceré. Saludos y espero respuestas

Christian Quispe

unread,
Jun 23, 2015, 7:11:43 PM6/23/15
to cakep...@googlegroups.com
Checa si la carpeta Plugins/Upload tenga archivos. Si está vacio ya sabes cual es el error.

Pablo

unread,
Jun 23, 2015, 7:13:38 PM6/23/15
to cakep...@googlegroups.com

Ya chequeaste lo q menciona el error?

--
Has recibido este mensaje porque estás suscrito al grupo "CakePHP en Español" de Grupos de Google.
Para anular la suscripción a este grupo y dejar de recibir sus mensajes, envía un correo electrónico a cakephp-esp...@googlegroups.com.
Para publicar en este grupo, envía un correo electrónico a cakep...@googlegroups.com.
Visita este grupo en http://groups.google.com/group/cakephp-esp.
Para acceder a más opciones, visita https://groups.google.com/d/optout.

detectivejd

unread,
Jun 24, 2015, 9:35:50 PM6/24/15
to cakep...@googlegroups.com
Hola, recién veo los mensajes y gracias x responder, la cuestión es que tiene carpetas y archivos.



sobre este errores: The application is trying to load a file from the Upload plugin y Make sure your plugin Upload is in the app/Plugin directory and was loaded, estan en:

app
     ->
        Plugin
                  ->
                     Upload

pero no me doy cuenta de la falla, espero sus respuestas y saludos.

detectivejd

unread,
Jun 24, 2015, 9:57:29 PM6/24/15
to cakep...@googlegroups.com
Miren que lo arrglé el problema poniendo CakePlugin::loadAll(); y cambié mi método add por este código:

if ($this->request->is('post')) {
            $nombrearchivo = "app/webroot/files/".$this->data['Aparato']['id_foto']['name'];
            if (move_uploaded_file($this->request->data['Aparato']['id_foto']['tmp_name'],$nombrearchivo)) {
                $this->Aparato->create();
                if ($this->Aparato->save($this->request->data)) {
                    $this->Session->setFlash(__('Aparato Guardado'));
                    $this->redirect(array('action' => 'index'));
                } 
                else {
                    $this->Session->setFlash(__('error al crear aparato'));
                }
            }
        }

en mi modelo Aparato lo tengo así:

class Aparato extends AppModel {
    public $actsAs = array(
        'Upload.Upload' => array(
            'id_foto' => array(
                'fields' => array(
                    'dir' => 'dir'
                ),                
                'thumbnailSizes' => array(
                    'big' => '200x200',
                    'small' =>'120x120',
                    'thumb' =>'80x80'
                ),
                'thumbnailMethod'=> 'php'
            )
        )
    );
}

pero me salen los sgtes errores:

Warning (2): move_uploaded_file(app/webroot/files/descarga.jpg): failed to open stream: No such file or directory [APP/Controller/AparatosController.php, line 24]
Warning (2): move_uploaded_file() [function.move-uploaded-file]: Unable to move '/opt/lampp/temp/phpjnGPrr' to 'app/webroot/files/descarga.jpg' [APP/Controller/AparatosController.php, line 24]

no me doy cuenta de la falla o de q más cambiar, espero sus respuestas y saludos.

detectivejd

unread,
Jun 27, 2015, 11:40:15 PM6/27/15
to cakep...@googlegroups.com
hola a todos, revisando links y código volví a cambiar quedandome de esta forma:

en View/Aparatos/add.ctp

<?php 
    echo $this->Form->create('add_aparato', array('type' => 'file'));
        echo $this->Form->input("nombre");
        echo $this->Form->input("descrip");
        echo $this->Form->input('id_foto', array('type' => 'file', 'label' => 'Foto'));
        echo $this->Form->input('dir', array('type' => 'hidden'));
        echo $this->Form->submit("Aceptar");
    echo $this->Form->end();
    echo $this->Html->link("[Cancelar]", array('action'=>'index')); 
?>

en AparatosController:

<?php
App::uses('AppController', 'Controller');
/**
 * CakePHP AparatoController
 * @author detectivejd
 */
class AparatosController extends AppController {
    public $helpers = array ('Html','Form');
    public function index() {
        
    }
    public function add() {      
        if ($this->request->is('post')){
            $this->Aparato->create();
            if ($this->Aparato->save($this->request->data)){
                $this->Session->setFlash('Registro guardado','default', array('class' => 'alert alert-success'));
                $this->redirect(array('action'=>'index'));
            } else {
                $this->Session->setFlash('Error al crear registro', array('class' => 'alert alert-danger'));
            }
        }
    }
}

en Model/Aparato.php

<?php
App::uses('AppModel', 'Model');
/**
 * CakePHP Aparato
 * @author detectivejd
 */
class Aparato extends AppModel {
    public $actsAs = array(
        'Upload.Upload' => array(
            'foto' => array(
                'fields' => array(
                    'dir' => 'foto_dir'
                ),           
                'thumbnailMethod'  => 'php',
                'thumbnailSizes' => array(
                    'big' => '200x200',
                    'small' =>'120x120',
                    'thumb' =>'80x80'
                ),
                'deleteOnUpdate' => true,
                'deleteFolderOnDelete' => true
            )
        )
    );
}

y a la hora de ejecutarlo me tiran los sgtes errores:

Warning (2): strpos() expects parameter 1 to be string, array given [CORE/Cake/basics.php, line 251]
Warning (2): explode() expects parameter 2 to be string, array given [CORE/Cake/basics.php, line 252]
Notice (8): Array to string conversion [CORE/Cake/View/View.php, line 1106]
Notice (8): Array to string conversion [CORE/Cake/View/View.php, line 1106]
Notice (8): Array to string conversion [CORE/Cake/View/View.php, line 1106]
Warning (2): strpos() expects parameter 1 to be string, array given [CORE/Cake/basics.php, line 251]
Warning (2): explode() expects parameter 2 to be string, array given [CORE/Cake/basics.php, line 252]
Notice (8): Undefined offset: 0 [CORE/Cake/basics.php, line 254]
Notice (8): Undefined offset: 1 [CORE/Cake/View/View.php, line 422]
Notice (1024): Element Not Found: .Elements/.ctp [CORE/Cake/View/View.php, line 425]

La verdad es que no se me ocurre nada, comienzo a pensar que el error podría estar en que me falta alguna carpeta o algo que no sé, adjunté mi código xq no me doy cuenta en dónde esta mi falla.
Agradeceré cualquier comentario y ayuda. Saludos
CheloMountain.tar.gz
Message has been deleted

detectivejd

unread,
Jun 28, 2015, 7:47:46 PM6/28/15
to cakep...@googlegroups.com
Hola a todos, les cuento que solucioné el tema de subir imagenes, todo lo q hice fue cambiar un poco el código y funciona para agregar:

en View/Aparatos/add.ctp:

<div class="page-header">
<h2>Crear Aparato</h2>
</div>
<?php 
    echo $this->Form->create('Aparato', array('type' => 'file', 'novalidate' => 'novalidate'));
        echo $this->Form->input("nombre");
        echo $this->Form->input("descrip");
        echo $this->Form->input('foto', array('type' => 'file', 'label' => 'Foto'));
        echo $this->Form->input('foto_dir', array('type' => 'hidden'));
    echo $this->Form->end(array('label' => 'Aceptar', 'class' =>'btn btn-success'));
    echo $this->Html->link("[Cancelar]", array('action'=>'index')); 
?>

en AparatosController:

public function add() {      
        if ($this->request->is('post')){
            $this->Aparato->create();
            if ($this->Aparato->save($this->request->data)){
                $this->Session->setFlash('Registro guardado','default', array('class' => 'alert alert-success'));
                $this->redirect(array('action'=>'index'));
            } else {
                $this->Session->setFlash('Error al crear registro', array('class' => 'alert alert-danger'));
            }
        }
    }

pero ahora para el tema de las validaciones y para editar el aparato, no funcionada el tema de las imagenes para editar los aparatos y para las validaciones tanto para crear como para editar aparatos, aquí subo el código:

en View/Aparatos/add.ctp:

<div class="page-header">
<h2>Editar Aparato</h2>
</div>
<?php 
    echo $this->Form->create('Aparato', array('type' => 'file', 'novalidate' => 'novalidate'));
        echo $this->Form->input('id', array('type' => 'hidden'));
        echo $this->Form->input("nombre");
        echo $this->Form->input("descrip");
        echo $this->Form->input('foto', array('type' => 'file', 'label' => 'Foto'));
        echo $this->Form->input('foto_dir', array('type' => 'hidden'));
    echo $this->Form->end(array('label' => 'Aceptar', 'class' =>'btn btn-success'));    
    echo $this->Html->link("[Cancelar]", array('action'=>'index')); 
?>

en AparatosController:

public function edit($id =null){
        if (!$this->Aparato->findById($id)) {
            throw new NotFoundException('El registro no existe');
        }
        if ($this->request->is(array('post', 'put'))) {
            $this->Aparato->id = $id;
            if ($this->Aparato->save($this->request->data)) {
                $this->Session->setFlash('Registro Editado',array('class' => 'alert alert-success'));
                $this->redirect(array('action' => 'index'));
            }
            else{
                $this->Session->setFlash('Error al editar registro',array('class' => 'alert alert-danger'));             
            }
        }
        else{
            $options = array('conditions' => array('Aparato.' . $this->Aparato->primaryKey => $id));
            $this->request->data = $this->Aparato->find('first', $options);
        }
    }

en Model/Aparato.php:

    public $validate=array(
        'nombre' => array(
            'notEmpty' => array(
'rule' => 'notEmpty',
                'message' => 'Ingrese Nombre del Aparato',
            ),
            'isUnique' => array(
                'rule' => 'isUnique',
                'message' => 'El Aparato ya Existe',
                'on' => 'create'
            )
        ),
        /*
        'descrip'=>array(
            
        ),*/
        'foto' => array(
            'uploadError' => array(
                'rule' => 'uploadError',
                'message' => 'Algo anda mal, intente nuevamente',
                'on' => 'create'
            ),
    'isUnderPhpSizeLimit' => array(
                'rule' => 'isUnderPhpSizeLimit',
                'message' => 'Archivo excede el límite de tamaño de archivo de subida'
            ),
            'isValidMimeType' => array(
                'rule' => array('isValidMimeType', array('image/jpeg', 'image/png'), false),
                'message' => 'La imagen no es jpg ni png',
            ),
            'isBelowMaxSize' => array(
                'rule' => array('isBelowMaxSize', 1048576),
                'message' => 'El tamaño de imagen es demasiado grande'
    ),
            'isValidExtension' => array(
                'rule' => array('isValidExtension', array('jpg', 'png'), false),
                'message' => 'La imagen no tiene la extension jpg o png'
    ),
            'checkUniqueName' => array(
                'rule' => array('checkUniqueName'),
                'message' => 'La imagen ya se encuentra registrada',
                'on' => 'update'
            )
        )
    );
    function checkUniqueName($data){
        $isUnique = $this->find('first', array('fields' => array('Aparato.foto'), 'conditions' => array('Aparato.foto' => $data['foto'])));
return !empty($isUnique) ? false : true;
    }
}

pido si alguien me puede dar una idea de dónde me estoy equivocando, si alguien me puede dar una mano se los agradeceré.

Saludos.

PD: Adjunto una imagen con los errores que salen
Captura de pantalla de 2015-06-28 20:46:32.png

detectivejd

unread,
Jul 10, 2015, 8:34:01 PM7/10/15
to cakep...@googlegroups.com
Hola a todos, les cuento que solucioné mi problema, el error estaban en los setFlash de los métodos add y edit de AparatosController, quedándome así:

Controller: AparatosController.php: 

public function add() {          
        if ($this->request->is('post')){
            $this->Aparato->create();
            if ($this->Aparato->save($this->request->data)){
                $this->Session->setFlash('Registro guardado');
                $this->redirect(array('action'=>'index'));
            } else {
                $this->Session->setFlash('Error al crear registro');
            }
        }
    }

    public function edit($id =null){
        if (!$this->Aparato->findById($id)) {
            throw new NotFoundException('El registro no existe');
        }
        if ($this->request->is(array('post', 'put'))) {
            $this->Aparato->id = $id;
            if ($this->Aparato->save($this->request->data)) {
                $this->Session->setFlash('Registro Editado');
                $this->redirect(array('action' => 'index'));
            }
            else{
                $this->Session->setFlash('Error al editar registro');             
            }
        }
        else{
            $options = array('conditions' => array('Aparato.' . $this->Aparato->primaryKey => $id));
            $this->request->data = $this->Aparato->find('first', $options);
        }
    } 

view/Aparatos/add.ctp:

<div class="container">
    <div class="row">
        <div class="col-md-6">
            <?php echo $this->Form->create('Aparato', array('type' => 'file', 'novalidate' => 'novalidate')); ?>
            <fieldset>
                <legend>Crear Aparato</legend>
                <?php 
                    echo $this->Form->input('nombre', array('class' => 'form-control', 'label' => 'Nombre del Aparato:'));
                    echo $this->Form->input('descrip', array('class' => 'form-control', 'label' => 'Descripción del Aparato:'));
                    echo $this->Form->input('foto', array('type' => 'file', 'label' => 'Foto del Aparato:'));
                    echo $this->Form->input('foto_dir', array('type' => 'hidden'));
                ?>
            </fieldset>
            <?php echo $this->Form->end(array('label' => 'Aceptar', 'class' =>'btn btn-success')); ?>
            <p>
                <?php echo $this->Html->link("[Cancelar]", array('action'=>'index')); ?>
            </p>
        </div>
    </div>
</div>

view/Aparatos/edit.ctp:

<div class="container">
    <div class="row">
        <div class="col-md-6">
            <?php echo $this->Form->create('Aparato', array('type' => 'file', 'novalidate' => 'novalidate')); ?>
                <fieldset>
                    <legend>Editar Aparato</legend>
                    <?php 
                        echo $this->Form->input('id', array('type' => 'hidden'));
                        echo $this->Form->input('nombre', array('class' => 'form-control', 'label' => 'Nombre del Aparato:'));
                        echo $this->Form->input('descrip', array('class' => 'form-control', 'label' => 'Descripción del Aparato:'));
                        echo $this->Form->input('foto', array('type' => 'file', 'label' => 'Foto del Aparato:'));
                        echo $this->Form->input('foto_dir', array('type' => 'hidden'));
                    ?>
                </fieldset>
            <?php echo $this->Form->end(array('label' => 'Aceptar', 'class' =>'btn btn-success')); ?>
            <p>
                <?php echo $this->Html->link("[Cancelar]", array('action'=>'index')); ?>
            </p>               
        </div>
    </div>
</div>

Model: Aparato.php

<?php
App::uses('AppModel', 'Model');
/**
 * CakePHP Aparato
 * @author detectivejd
 */
class Aparato extends AppModel {
    public $displayField = 'nombre';
    /*-------------------------------*/
    public $actsAs = array(
        'Upload.Upload' => array
            (
                'foto' => array(
                    'fields' => array(
                        'dir' => 'foto_dir'
                    ),           
                    'thumbnailMethod'=> 'php',
                    'thumbnailSizes' => array
                    (
                            'vga' => '640x480',
                            'thumb' => '150x150'
                    ),
                'deleteOnUpdate' => true,
                'deleteFolderOnDelete' => true
            )
        )
    );
    /*--------------------------------*/
    public $validate=array(
        'nombre' => array(
            'notEmpty' => array(
'rule' => 'notEmpty',
                'message' => 'Ingrese Nombre del Aparato',
            ),
            'isUnique' => array(
                'rule' => 'isUnique',
                'message' => 'El Aparato ya Existe',
                'on' => 'create'
            )
        ),

usando el plugin Upload y anda de maravillas, gracias a todos los que me ayudaron, ahora para terminar con esta parte del sistema tengo q ver cómo hacer que los mensajes de error y mensajes de afirmación sean de estilo diferente en los setFlash.

Saludos

Jose Julian Abarca

unread,
Jul 11, 2015, 3:35:40 PM7/11/15
to cakep...@googlegroups.com
Saludos!!

--

Juandy Ocampo

unread,
Jul 11, 2015, 8:10:01 PM7/11/15
to cakep...@googlegroups.com
Gracias, el problema de las imagenes esta resuelto, ahora para tener pronto lo de las funcionalidades add, edit y remove me falta ver cómo hacer para cambiar el aspecto de los setFlash en caso de si el mensaje es de error o un mensaje afirmativo.

Acepto sugerencias y ideas.

Saludos.

detectivejd

unread,
Jul 17, 2015, 8:04:37 PM7/17/15
to cakep...@googlegroups.com
problema de los mensajes resuelto, tuve que integrar bootstrap y solucionado. Saludos
Reply all
Reply to author
Forward
0 new messages