Foros del Web » Programando para Internet » PHP » Frameworks y PHP orientado a objetos »

[SOLUCIONADO] Subir Imagenes en CakePhp 2.6

Estas en el tema de Subir Imagenes en CakePhp 2.6 en el foro de Frameworks y PHP orientado a objetos en Foros del Web. 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 ...
  #1 (permalink)  
Antiguo 22/06/2015, 21:09
Avatar de detective_jd  
Fecha de Ingreso: abril-2011
Ubicación: Salto
Mensajes: 437
Antigüedad: 13 años
Puntos: 6
Subir Imagenes en CakePhp 2.6

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:

Error: 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
  #2 (permalink)  
Antiguo 28/06/2015, 17:47
Avatar de detective_jd  
Fecha de Ingreso: abril-2011
Ubicación: Salto
Mensajes: 437
Antigüedad: 13 años
Puntos: 6
Respuesta: Subir Imagenes en CakePhp 2.6

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:

<?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
)
)
);
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;
}
}

Estos son los errores que me salen:

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]

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
  #3 (permalink)  
Antiguo 12/07/2015, 17:54
Avatar de detective_jd  
Fecha de Ingreso: abril-2011
Ubicación: Salto
Mensajes: 437
Antigüedad: 13 años
Puntos: 6
Respuesta: Subir Imagenes en CakePhp 2.6

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'
)
),
- mostrar texto citado -

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

Etiquetas: cakephp, imagenes, php
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 19:55.