Welcome, Guest. Register Now!
   
Mark Forums Read Mark Forums Read Mark Forums Read


Reply
 
LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 08-06-2007, 05:22 PM
matias.quaglia's Avatar
Junior Member
 
Join Date: Aug 2007
Posts: 18
Lightbulb [ALMOST SOLVED] $_FILES in MVC

Hi everybody!

I'm trying to learn to use ZF.

I decided to make a very simple image gallery application using MVC architecture.

I took the idea from the phpRiot tutorial on storing images on mysql (you can check it out here).

I want to upload an image file, then read its content and store the binaries in a mysql table.

I've created a trivial Model, an ImageController with a few actions like add, delete, list on it.

models/Image.php
PHP Code:
class Image extends Zend_Db_Table 
{
    protected 
$_name "image";
    

views/scripts/image/add.phtml:
PHP Code:
<?php echo $this->render('imageHeader.phtml');?>

<h3>Seleccione una Imagen para Subir</h3>
 
<form enctype="multipart/form-data" action="/image/add" method="post">
    <input type="hidden" name="MAX_FILE_SIZE" value="10000000" />
    <label>Imagen: </label><input name="foto[]" type="file" />
    <label>Nombre: </label><input name="name" type="text" />
    <label>Descripcion: </label><input name="description" type="text" />
    <input type="submit" value="Submit" />
</form>

<?php echo  $this->render('imageFooter.phtml');?>
controllers/ImageController.php
PHP Code:
class ImageController extends Zend_Controller_Action 
{
    function 
init()
    {
        
$this->view->baseUrl $this->_request->getBaseUrl();
        
Zend_Loader::loadClass("Image");
        
date_default_timezone_set('America/Buenos_Aires');
    }
    
    function 
indexAction() 
    {
        
$this->view->title "Imágenes";
    }
    
    function 
addAction()
    {
        
        
        
$this->view->title "Agregar Imagen";
        if (
$this->_request->isPost()) {
            
            if (
is_uploaded_file($_FILES['foto']['tmp_name'])) {
                
                
Zend_Loader::loadClass('Zend_Filter_RealPath');
                
Zend_Loader::loadClass('Zend_Filter_StripTags');
                
Zend_Loader::loadClass('Zend_Date');
                
$fecha = new Zend_Date();
                
$filtroPath = new Zend_Filter_RealPath();
                
$filtroTags = new Zend_Filter_StripTags();
                
                
$binarios $filtroPath->filter(file_get_contents($_FILES['foto']['tmp_name']));
                
$infoImagen getimagesize($_FILES['foto']['tmp_name']);
                
$ahora $fecha->get();
                
                
$nombre $filtroTags->filter(trim($this->_request->getPost('nombre')));
                
$descripcion $filtroTags->filter(trim($this->_request->getPost('descripcion')));
                
                
$data = array(
                    
'mime_type'     => $infoImagen['mime'],
                    
'binary'        => $binarios,
                    
'size'            => $infoImagen[3],
                    
'created_on'    => $ahora,
                    
'name'            => $nombre,
                    
'description'    => $descripcion
                
);
                
                
$imagen = new Image();
                
$imagen->insert($data);
                
                if(!
$imagen) {
                    
$this->view->mensaje 'Error al insertar datos';
                } else {
                    
$this->view->mensaje 'Foto Exitosamente agregada en el registro '.$imagen;
                }
                
            } else {
                
                
$this->view->mensaje 'Error al subir la foto';
                
            }
            
        }
    }
    
    function 
deleteAction()
    {
        
    }
    
    function 
viewAction()
    {
        
    }


and my public/index.php with bottstrap

PHP Code:
ini_set('include_path',ini_get('include_path').'.:/home/novuste/zf/library');

//vemos todos los errores
error_reporting(E_ALL|E_STRICT);

//incluimos un par más de cosas en el include path
set_include_path('.' PATH_SEPARATOR '../application/models/' PATH_SEPARATOR get_include_path());

//incluimos una clase loader... ¿por el solo hecho de incluira ya instanciamos la clase?
include "Zend/Loader.php";

//Cargamos la clase de configuración a través de ini y la clase de manejo del registro del framework
Zend_Loader::loadClass('Zend_Config_Ini');
Zend_Loader::loadClass('Zend_Registry');

//creamos un nuevo objeto de confoguracion y cargamos el .ini, la seccion general
$config = new Zend_Config_Ini('../application/config.ini''general'false);
$registry Zend_Registry::getInstance();
$registry->set('config'$config);

//cargamos la clase de manejo de bases de datos y tablas
Zend_Loader::loadClass('Zend_Db');
Zend_Loader::loadClass('Zend_Db_Table');

//creamos un nuevo objeto base de datos, y asigna a la tabla ese objeto de configuración
$db Zend_Db::factory($config->db->adapter$config->db->config->toArray());
Zend_Db_Table::setDefaultAdapter($db);

//Cargamos la clase Controller para el front end
Zend_Loader::loadClass('Zend_Controller_Front');

//cargamos el objeto, le permitos lanzar excepciones, configuramos el directorio de controladores, y despachamos
$frontController Zend_Controller_Front::getInstance();
$frontController->throwExceptions(true);
$frontController->setControllerDirectory('../application/controllers');

$frontController->dispatch(); 
When i try to upload any image i just receive something like Notice: Array to string conversion in application/controllers/ImageController.php on line 23, and the image isn't uploaded, can anybody give me a tip?
What am i doing wrong?
How can i access in the controller, to the file sended via multipart post form in view?

Thank you!
__________________
Matías Quaglia
==========
http://www.matiasquaglia.com.ar
Credo est Creo

Last edited by matias.quaglia : 08-07-2007 at 12:13 PM.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #2 (permalink)  
Old 08-07-2007, 12:03 PM
matias.quaglia's Avatar
Junior Member
 
Join Date: Aug 2007
Posts: 18
Default

Well, I already figure it out.

I quit (just for now) the RealPath filtering to get the file contents:

Here, my add image action
PHP Code:

    
function addAction()
    {
        
$this->view->title "Agregar Imagen";
        if (
$this->_request->isPost()) {
            
            if (
is_uploaded_file($_FILES['foto']['tmp_name'])) {
                
                
Zend_Loader::loadClass('Zend_Filter_StripTags');
                
$filtroTags = new Zend_Filter_StripTags();
                
$nombre $filtroTags->filter(trim($this->_request->getPost('nombre')));
                
$descripcion $filtroTags->filter(trim($this->_request->getPost('descripcion')));
                
                
Zend_Loader::loadClass('Zend_Date');
                
$fecha = new Zend_Date();
                
$ahora $fecha->get();
                
                
$binarios file_get_contents($_FILES['foto']['tmp_name']);
                
$infoImagen getimagesize($_FILES['foto']['tmp_name']);
                
                
$data = array(
                    
'mime_type'     => $infoImagen['mime'],
                    
'binary'        => $binarios,
                    
'size'            => $infoImagen[3],
                    
'created_on'    => $ahora,
                    
'name'            => $nombre,
                    
'description'    => $descripcion
                
);
                
                
$imagen = new Image();
                
$idImagen $imagen->insert($data);
                
                if(!
$idImagen) {
                    
$this->view->mensaje 'Error al insertar datos';
                } else {
                    
$this->view->mensaje "Foto Exitosamente agregada en el registro $idImagen";
                }
                
                
unlink($_FILES['foto']['tmp_name']);
                
            } else {
                
                
$this->view->mensaje 'Error al subir la foto';
                
            }
            
        } else {
            
            
$this->view->mensaje 'Seleccione una Imagen para Subir';
            
        }
    } 
And here, my view:

PHP Code:
    function viewAction()
    {
        
$this->view->title "Ver Imagen";
        if (
$this->_hasParam('id')) {
            
            
$id $this->_getParam('id');
            
            
$imagen = new Image();
            
            
$imagenData $imagen->fetchRow("id = $id");
            
            if (
$imagenData) {
                
$this->view->imagen $imagenData;
                
$this->view->error 0;
            } else {
                
$this->view->error 1;
                
$this->view->mensaje "La imagen pedida ya no existe";
            }
            
            
        } else {
            
            
$this->view->error 2;
            
$this->view->mensaje "Debe indicar una imagen para abrir";
        }
    } 
Now my question is:

Is there a more elegant way to hadle uploaded files than the $_FILES php-super-global-array in ZF?
__________________
Matías Quaglia
==========
http://www.matiasquaglia.com.ar
Credo est Creo
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #3 (permalink)  
Old 10-28-2007, 05:02 AM
Junior Member
 
Join Date: Oct 2007
Posts: 1
Unhappy

Can you send me your application's source code?
I'm having problem with files upload using ZF!!
I don't know why I can't upload anything with ZF.I uploaded files successfully in a test application not using ZF.But whenever I use ZF,I can't upload even 1 small file!!
__________________
Hope you will tolerate my bad english.

Last edited by plhoangan : 10-28-2007 at 05:23 AM.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Reply


Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On



All times are GMT. The time now is 10:41 PM.