New way to upload file in symfony

Controller code :

namespace Profile\ProfileBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Profile\RegisterBundle\Entity\User;
use Profile\RegisterBundle\Form\UserType;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Profile\ProfileBundle\Models\Document;
use Profile\ProfileBundle\Entity\Userfile;
class DefaultController extends Controller
{

public function indexAction(Request $request)
{
$usertype =new User();
$session =$this->getRequest()->getSession();
$userlogin = $session->get(‘userlogin’);
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository(‘ProfileRegisterBundle:User’)->find($userlogin);
if (!$entity) {
throw $this->createNotFoundException(‘Unable to find  entity.’);
}
if($request->getMethod()==POST)
{
$image=$request->files->get(‘img’);
$status = ‘success’;
$uploadedURL=”;
$message=”;

if (($image instanceof UploadedFile) && ($image->getError() == ‘0’)) {
if (($image->getSize() < 2000000000)) {
$originalName = $image->getClientOriginalName();
$name_array = explode(‘.’, $originalName);
$file_type = $name_array[sizeof($name_array) – 1];
$valid_filetypes = array(‘jpg’, ‘jpeg’, ‘bmp’, ‘png’);
if (in_array(strtolower($file_type), $valid_filetypes)) {
//Start Uploading File

$document = new Document();
$document->setFile($image);
$document->setSubDirectory(‘uploads’);

$document->processFile();

$uploadedURL=$uploadedURL = $document->getUploadDirectory() . DIRECTORY_SEPARATOR . $document->getSubDirectory() . DIRECTORY_SEPARATOR . $image->getBasename();

$imgname=$image->getBasename().’.’.$file_type;

$userVal=new Userfile();
$userVal->setFilename($imgname);
$userVal->setUserid($userlogin);

$em=$this->getDoctrine()->getEntityManager();
$em->persist($userVal);
$em->flush();

} else {
$status = ‘failed’;
$message = ‘Invalid File Type’;
}
} else {
$status = ‘failed’;
$message = ‘Size exceeds limit’;
}
} else {
$status = ‘failed’;
$message = ‘File Error Please try again’;

}
return $this->render(‘ProfileProfileBundle:Default:index.html.twig’,array(‘status’=>$status,’message’=>$message,’uploadedURL’=>$uploadedURL,’record’=>$entity));

}
else
{

return $this->render(‘ProfileProfileBundle:Default:index.html.twig’,array(‘userlogin’=>$userlogin,’record’=>$entity));
}
}
}

view page:

{% extends “TwigBundle::layout.html.twig” %}

{% block body -%}

<div>
<div>
<div>
<div>
<div><article>

<div><div>
<div>
{%if status is not defined %}
<form action=”{{ path(‘profile_profile_homepage’) }}”    method=”post” enctype=”multipart/form-data”>

<div>Welcome to  : {{record.firstname}}{{record.lastname}}</div>

<div>Email  : {{record.email}}</div>
<div>Profile Photo<input type=”file” name=”img”> </div>
<div>
<button type=”submit” name=”submit”>upload</button>
</div>
</form>
</div>
</div>
<div>
</div>
</div>
</article>
</div>
</div>
</div>
</div>

{% elseif status==’success’%}
{% if uploadedURL is defined%}
<img src=”{{asset(uploadedURL)}}”>
{% endif %}
{% else %}
{% if message is defined%}
<div>
<p>{{message}}</p>
</div>
{% endif %}
{% endif %}

{% endblock %}

routing :

profile_profile_homepage:
pattern:  /profile/profile/
defaults: { _controller: ProfileProfileBundle:Default:index }

Models:  Document.php

<?php
namespace Profile\ProfileBundle\Models;

/**
* Description of Document
*
* @author Vinod
*/
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()
{
if (! ($this->file instanceof UploadedFile) ) {
return false;
}
$uploadFileMover = new UploadFileMover();
$this->filePersistencePath = $uploadFileMover->moveUploadedFile($this->file, self::getUploadDirectory(),$this->subDir);
}
}
?>

Models

UploadfileMover.php

<?php

namespace Profile\ProfileBundle\Models;

/*
* 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) {
$originalName = $file->getFilename();
// 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);
}

}

?>

make folder in /web/uploads/uploads

Field Type Null Default Comments
id int(11) No
userid int(11) No
filename varchar(255) No

thanks

vinod

Advertisements

2 thoughts on “New way to upload file in symfony

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s