ccc

Symfony: Upload ficheros

Creamos en el proyecto una nueva entidad llamada "ficheros" con los campos id, nomFichero y descFichero

Creamos la carpeta \src\edcBundle\Utilidades y dentro de ella copiamos estos dos ficheros:
Document.php:
<?php
namespace edcBundle\Utilidades;

/**
 * Description of Document
 *
 * @author Manoj
 */
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;


class Document
{
    private $file;
   
    private $subDir;
   
    private $filePersistencePath;
   
    /** @var string */
    protected static $uploadDirectory = '%kernel.root_dir%/../uploads';
   
    static public function setUploadDirectory($dir)
    {
        self::$uploadDirectory = $dir;
    }
   
    static public function getUploadDirectory()
    {
        if (self::$uploadDirectory === null) {
            throw new \RuntimeException("Trying to access upload directory for profile files");
        }
        return self::$uploadDirectory;
    }
    public function setSubDirectory($dir)
    {
         $this->subDir = $dir;
    }
   
    public function getSubDirectory()
    {
        if ($this->subDir === null) {
            throw new \RuntimeException("Trying to access sub directory for profile files");
        }
        return $this->subDir;
    }
   
  
    public function setFile(File $file)
    {
        $this->file = $file;
    }
   
    public function getFile()
    {
        return new File(self::getUploadDirectory() . "/" . $this->filePersistencePath);
    }
   
     public function getOriginalFileName()
    {
        return $this->file->getClientOriginalName();
    }
   
    public function getFilePersistencePath()
    {
        return $this->filePersistencePath;
    }
   
    public function processFile($nomDefinitivo)
    {
        if (! ($this->file instanceof UploadedFile) ) {
            return false;
        }
        $uploadFileMover = new UploadFileMover();
        $this->filePersistencePath = $uploadFileMover->moveUploadedFile($this->file, self::getUploadDirectory(),$this->subDir, $nomDefinitivo);
    }
}

UploadFileMover.php:
<?php
namespace edcBundle\Utilidades;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

use Symfony\Component\HttpFoundation\File\UploadedFile;

/**
 * Description of UploadFileMover
 *
 * @author Manoj
 */
class UploadFileMover {

    public function moveUploadedFile(UploadedFile $file, $uploadBasePath,$relativePath,$nomDefinitivo) {
        // $originalName = $file->getFilename();
        $originalName = $nomDefinitivo;
        // use filemtime() to have a more determenistic way to determine the subpath, otherwise its hard to test.
       // $relativePath = date('Y-m', filemtime($file->getPath()));
        $targetFileName = $relativePath . DIRECTORY_SEPARATOR . $originalName;
        $targetFilePath = $uploadBasePath . DIRECTORY_SEPARATOR . $targetFileName;
        $ext = $file->getExtension();
        $i=1;
        while (file_exists($targetFilePath) && md5_file($file->getPath()) != md5_file($targetFilePath)) {
            if ($ext) {
                $prev = $i == 1 ? "" : $i;
                $targetFilePath = $targetFilePath . str_replace($prev . $ext, $i++ . $ext, $targetFilePath);
               
            } else {
                $targetFilePath = $targetFilePath . $i++;
            }
        }


        $targetDir = $uploadBasePath . DIRECTORY_SEPARATOR . $relativePath;
        if (!is_dir($targetDir)) {
            $ret = mkdir($targetDir, umask(), true);
            if (!$ret) {
                throw new \RuntimeException("Could not create target directory to move temporary file into.");
            }
        }
        $file->move($targetDir, basename($targetFilePath));
        return str_replace($uploadBasePath . DIRECTORY_SEPARATOR, "", $targetFilePath);
    }
}

Creamos el controlador UploadController.php:
<?php
namespace edcBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use edcBundle\Utilidades\Document;
use edcBundle\Entity\ficheros;

class UploadController extends Controller
{
    public function indexAction()
    {
        // return $this->render('edcBundle:Default:index.html.twig');
    }

    // ****************************************
    public function subiendo($fichSubir, $descripcion) {
        if (($fichSubir instanceof UploadedFile) && ($fichSubir->getError() == '0'))
        {
            $originalName = $fichSubir->getClientOriginalName();
            $name_array = explode('.', $originalName);
            $file_type = $name_array[sizeof($name_array) - 1];
            $valid_filetypes = array('jpg', 'jpeg');
            if(in_array(strtolower($file_type), $valid_filetypes))
            {
                $document = new Document();
                $document->setFile($fichSubir);
                $document->setSubDirectory('ficheros');
                $nomDefinitivo = "1234_".$originalName; // por ejemplo el id de un usuario
                // Si queremos q lo guarde con un nombre al azar entonces será:
                // $nomDefinitivo = $fichSubir->getFilename();
                $document->processFile($nomDefinitivo);
               
                // Una vez subido, meterlo en la BD
                $ficheroAux = new ficheros();
                $ficheroAux->setDescFichero($descripcion);
                $ficheroAux->setNomFichero($nomDefinitivo);
               
                $em = $this->getDoctrine()->getManager();
                $em->persist($ficheroAux);
                $em->flush();
                //redireccinar
                $this->get('session')->getFlashBag()->add(
                        'mensaje',
                        'El archivo '.$originalName.' se ha subido correctamente'
                );
                //redirecciono
                return $this->redirect($this->generateUrl('subirArchivo'));
            }else
            {
                $this->get('session')->getFlashBag()->add(
                        'mensaje',
                        'la extensión del archivo no es la correcta'
                );
                //redireccionar
                return $this->redirect($this->generateUrl('subirArchivo'));
            }
        }else
        {
            $this->get('session')->getFlashBag()->add(
                    'mensaje',
                    '"no entró o se produjo algún error inesperado'
            );
            //redireccionar
            return $this->redirect($this->generateUrl('subirArchivo'));
            //die("no entró o se produjo algún error inesoperado");
        }
    }
   
    // **************************************************
    public function subirArchivoAction(Request $request)
    {
        if ($request->getMethod() == 'POST')
        {
             $arrArchivos = $request->files->get('archivo');
             $arrDescArchivo = $_POST["descArchivo"];
             $cont = 0;
             foreach ($arrArchivos as $clave => $valor) {
                 $this->subiendo($valor, $arrDescArchivo[$cont]);
                 $cont++;
             }
        }
        return $this->render('edcBundle:Upload:subirArchivo.html.twig');
    }
}

Crear la vista subirArchivo.html.twig:
{% extends 'edcBundle::viewEDC.html.twig' %}

{% block body %}
     {% for flashMessage in app.session.flashbag.get('mensaje') %}
    <span class="alert-success">
        {{ flashMessage }}
        <hr />
   
    </span>
    {% endfor %}
   
    <h1>Subir Archivo</h1>
    <form role="form" enctype="multipart/form-data" method="post" action="{{path('subirArchivo')}}">
       <div class="input-group">
           <p>
          ARCHIVO 1:
          <input type="file" name="archivo[]" class="form-control" id="exampleInputEmail2" />
        </p>
        <p>
          Nombre del archivo:
          <input type="text" name="descArchivo[]" class="form-control" >
        </p>
      </div>
        <hr>
        <div class="input-group">
            <p>
              ARCHIVO 2:
              <input type="file" name="archivo[]" class="form-control" id="exampleInputEmail2" />
            </p>
            <p>
              Nombre del archivo:
              <input type="text" name="descArchivo[]" class="form-control" >
            </p>
        </div>
        <hr />
        <button type="submit" class="btn btn-default">Enviar</button>
    </form>
{% endblock %}

No hay comentarios:

Publicar un comentario