0

I am trying to handle image uploads via a form and then display these image uploads elsewhere in my website.

So far I have been looking at the Cookbook and also at other tutorials.I have created an Entity and a Form and am able to submit , but I am not sure if I am storing the file itself in my DB or just the name of it.

When I try to display the images in my view resource not found error on the images. Any suggestions on the correct way to upload images in Symfony?

and this is what I have so far. Entity

<?php
namespace BlogBundle\Entity;
use Symfony\Component\HttpFoundation\File\File;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Photo
*
* 
* @ORM\Entity
* @ORM\HasLifecycleCallbacks
*/
class Upload 
{

/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
  /**
  *Image File
* @var File
* @Assert\File( maxSize = "5M",mimeTypes = {"image/jpeg", "image/gif",    "image/png", "image/tiff"}, mimeTypesMessage = "Please upload a valid Image")
  * 
  */
  private $file;
  /**
 * @ORM\Column(type="string", length=500)
 */
private $title;
/**
 * @ORM\Column(type="string", length=500)
 */
private $description;


/**
 * Image path
 *
 * @var string
 *
 * @ORM\Column(type="text", length=255, nullable=false)
 */
protected $path;


 protected function getUploadRootDir()
{
    return __DIR__.'/../../../../web/'.$this->getUploadDir();
}

 protected function getUploadDir()
{
    // get rid of the __DIR__ so it doesn't screw up
    // when displaying uploaded doc/image in the view.
    return 'uploads/documents';
}

/**
 * Get id
 *
 * @return integer 
 */
public function getId()
{
    return $this->id;
}

/**
 * Set title
 *
 * @param string $title
 * @return Upload
 */
public function setTitle($title)
{
    $this->title = $title;

    return $this;
}

/**
 * Get title
 *
 * @return string 
 */
public function getTitle()
{
    return $this->title;
}

/**
 * Set description
 *
 * @param string $description
 * @return Upload
 */
public function setDescription($description)
{
    $this->description = $description;

    return $this;
}

/**
 * Get description
 *
 * @return string 
 */
public function getDescription()
{
    return $this->description;
}

/**
 * Set path
 *
 * @param string $path
 * @return Upload
 */
public function setPath($path)
{
    $this->path = $path;

    return $this;
}

/**
 * Get path
 *
 * @return string 
 */
public function getPath()
{
    return $this->path;
}

/**
 * Called before saving the entity
 * @ORM\PrePersist()
 * @ORM\PreUpdate()
 */
 public function preUpload()
 {   
 if (null !== $this->file) {
    // do whatever you want to generate a unique name
    $filename = sha1(uniqid(mt_rand(), true));
    $this->path = $filename.'.'.$this->file->guessExtension();
}
}

/**
 * Called before entity removal
 *
 * @ORM\PreRemove()
 */
 public function removeUpload()
 {
  if ($file = $this->getAbsolutePath()) 
  {
    unlink($file); 
   }
 }

/**
* Called after entity persistence
*
* @ORM\PostPersist()
* @ORM\PostUpdate()
*/
public function upload()
{
// The file property can be empty if the field is not required
if (null === $this->file) {
    return;
}

// Use the original file name here but you should
// sanitize it at least to avoid any security issues

// move takes the target directory and then the
// target filename to move to
$this->file->move(
    $this->getUploadRootDir(),
     $this->getFile()->getClientOriginalName()
);

// set the path property to the filename where you've saved the file
$this->path = $this->getFile()->getClientOriginalName();


// Clean up the file property as you won't need it anymore
$this->file = null;
}

/**
 * Sets file.
 *
 * @param UploadedFile $file
 *@return Upload
 */
public function setFile(File $file = null)
{
    $this->file = $file;

}

/**
 * Get file.
 *
 * @return UploadedFile
 */
public function getFile()
{
    return $this->file;
}
    }

Controller methods

/** This is the homepage for the admin area, for adding,deleting,editing of blog posts.
 * @Route("/posted/admin/upload", name="upload")
 * @Template()
 */
 public function uploadimageAction(Request $request)
 {
 $upload = new Upload();


//create checkboxtype form
$form = $this->createForm(new ImageFormType(), $upload, array(
        'action' => $this->generateUrl('upload'),
        'method' => 'POST',
  ));

$form->handleRequest($request);

if($form->isValid()){
          $em = $this->getDoctrine()->getManager();
          $upload->upload();
          $em->persist($upload);
          $em->flush();
  //   exit(\Doctrine\Common\Util\Debug::dump($post));

      return $this->render('BlogBundle:Default:success.html.twig'


            );
            ;
}
return $this->render('BlogBundle:Default:upload.html.twig',array(
          'form' =>$form->createView(),

  ));
 }

1 Answer 1

1

You are only storing the path in the DB, and only it's necesary that.

Using path you can show the file in your view

pd: you are storing the file in your server with:

$this->file->move(
    $this->getUploadRootDir(),
    $this->getFile()->getClientOriginalName()
);
Sign up to request clarification or add additional context in comments.

6 Comments

When I try to call path in the twig though it just shows the name of the file? <img src="{{entity.path}}" alt="{{entity.title}}"> @Gonzalo1987
Probably, but you can set the UploadRootDir in the parameters of twig (config.yml file) and append both {{ uploadDir ~ '/' ~ entity.path }}
Sorry, not sure what I should write in my config.yml?
it's still not producing any output
¿not producing any output? what do you mean? In your question you haven't said anything about 'no output' -> 'in my view resource not found error on the images.'
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.