Symfony3.2 upload a file - php

i'm trying to upload a picture but i don't know why i always got this error message.
Error: Call to a member function guessExtension() on a non-object
this means that the object i got is null, but why?
this is my input<input type="file" id="images_emp" name="images_emp" >.
now in the contrller i did this:
$pic = $request->files->get('images_emp');
$imagenom=$nom.$Cin.'.'.$pic->guessExtension();
$pic->move( $this->getParameter('Dossier_images'),imagenom);
$Employe->setImgsrc("/images/".$imagenom);
and in this is what the entity looks like.
/**
* #ORM\Column(type="string", nullable=true)
*
* #Assert\File(
* maxSize = "1024k",
* mimeTypes={ "application/png" ,"application/jpg","application/jpeg"},
* mimeTypesMessage = "Svp inserer une forme valide (png,jpg,jpeg)"
* )
*/private $imgsrc;
/**
* #return mixed
*/
public function getImgsrc()
{
return $this->imgsrc;
}
/**
* #param mixed $imgsrc
*/
public function setImgsrc($imgsrc)
{
$this->imgsrc = $imgsrc;
return $this;
}
how could i solve this problem.

i advice you to use the events in entity is very simple and good then get()
Entity Images
<?php
namespace ------------ ;
use Symfony\Component\HttpFoundation\File\UploadedFile;
/**
* Images
*
* #ORM\Table(name="images")
* #ORM\Entity(repositoryClass="---------")
* #ORM\HasLifecycleCallbacks
*/
class Slides
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="url", type="string", length=255)
*/
private $url;
/**
* #var string
* #ORM\Column(name="alt", type="string", length=255)
*/
private $alt;
private $file;
//This attribute is added to store the temporary file name
private $tempFilename;
public function __construct()
{
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set url
*
* #param string $url
*
* #return Images
*/
public function setUrl($url)
{
$this->url = $url;
return $this;
}
/**
* Get url
*
* #return string
*/
public function getUrl()
{
return $this->url;
}
public function getFile()
{
return $this->file;
}
public function setFile(UploadedFile $file = null)
{
$this->file = $file;
// We check if we already had a file for this entity
if (null !== $this->url) {
// The file extension is saved to be deleted later
$this->tempFilename = $this->url;
// Reset the values of the url and alt attributes
$this->url = null;
$this->alt = null;
} }
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function preUpload()
{
// If there is no file (optional field), nothing is done
if (null === $this->file) {
return;
}
// The name of the file is its id, you just have to store its extension
// To make it clean, we should rename this attribute to "extension" instead of "url"
$this->url = $this->file->guessExtension();
// And we generate the alt attribute of the <img> tag, at the file name value on the user's PC
}
/**
* #ORM\PostPersist()
* #ORM\PostUpdate()
*/
public function upload()
{
//If there is no file (optional field), nothing is done
if (null === $this->file) {
return;
}
//If we had an old file, we delete it
if (null !== $this->tempFilename) {
$oldFile = $this->getUploadRootDir().'/'.$this->id.'.'.$this->tempFilename;
if (file_exists($oldFile)) {
unlink($oldFile);
}
}
// We move the file sent in the directory of your choice
$this->file->move(
$this->getUploadRootDir(), // Le répertoire de destination
$this->id.'.'.$this->url // Le nom du fichier à créer, ici « id.extension »
);
}
/**
* #ORM\PreRemove()
*/
public function preRemoveUpload()
{
// We temporarily save the file name because it depends on the id
$this->tempFilename = $this->getUploadRootDir().'/'.$this->id.'.'.$this->url;
}
/**
* #ORM\PostRemove()
*/
public function removeUpload()
{
// In PostRemove, we do not have access to the id, we use our saved name
if (file_exists($this->tempFilename)) {
// we delete the file
unlink($this->tempFilename);
}
}
public function getUploadDir()
{
// Returns the relative path to the image for a browser
return 'uploads';
}
protected function getUploadRootDir()
{
// We return the relative path to the image for our PHP code
return __DIR__.'/../../../../web/'.$this->getUploadDir();
}
public function getWebPath()
{
return $this->getUploadDir().'/'.$this->getId().'.'.$this->getUrl();
}
/**
* Set description
*
* #param string $alt
*
* #return Images
*/
public function setAlt($alt)
{
$this->alt = $alt;
return $this;
}
/**
* Get alt
*
* #return string
*/
public function getAlt()
{
return $this->alt
}
}
In controller
$images = new Images();
$form = $this->get('form.factory')->create(ImagesType::class, $images);
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($images);
$em->flush();
}
and you can find this solution in openclassroom more more detailed

Related

The file '/tmp/phpAtfqKp' does not exist when uploading Image using Symfony2 Sonata Admin Bundle

I hope you're doing well.
Can anyone help me with this error ? I'm trying to upload an image using doctrine, after the image is uploaded I get The file "/tmp/phpAtfqKp" does not exist. I'm using sonata admin bundle to create the entity.
I know that the image is uploaded because it is found in web/uploads/property and when going to the edit entity page all images are displayed without any problem.
Here is my Image entity:
<?php
namespace Hatch2Web\MainBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Validator\Constraints as Assert;
use Hatch2Web\MainBundle\Service\UrlService;
/**
* Images
*
* #ORM\Table(name="image")
* #ORM\Entity(repositoryClass="Hatch2Web\MainBundle\Repository\ImagesRepository")
* #ORM\HasLifecycleCallbacks()
*/
class Image
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255,nullable=true)
*/
private $name;
/**
* #var \DateTime
*
* #ORM\Column(name="created_at", type="datetime")
*/
private $createdAt;
/**
* #var \DateTime
*
* #ORM\Column(name="updated_at", type="datetime", nullable=true)
*/
private $updated_at;
/**
* #ORM\ManyToOne(targetEntity="Hatch2Web\MainBundle\Entity\Property", inversedBy="images")
*/
private $property;
/**
* #Assert\File(maxSize="50000000",
* mimeTypes = {"image/jpeg", "image/jpg","image/png", "image/gif", "image/x-ms-bmp"},
* mimeTypesMessage = "Please upload a valid Mime Type File")
*
*/
public $file;
/**
*
*
* string
*/
private $dummyUrl;
public function __construct()
{
$this->createdAt = new \DateTime();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Image
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set createdAt
*
* #param \DateTime $createdAt
* #return Image
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set property
*
* #param \Hatch2Web\MainBundle\Entity\Property $property
* #return Image
*/
public function setProperty(\Hatch2Web\MainBundle\Entity\Property $property = null)
{
$this->property = $property;
return $this;
}
/**
* Get property
*
* #return \Hatch2Web\MainBundle\Entity\Property
*/
public function getProperty()
{
return $this->property;
}
/** File Upload */
/**
* Get file.
*
* #return UploadedFile
*/
public function getFile()
{
return $this->file;
}
public function getUploadDir()
{
return 'uploads/properties';
}
/**
* Sets file.
*
* #param UploadedFile $file
*/
public function setFile(UploadedFile $file = null, $hash)
{
if ($file) {
$this->file = $file;
$this->name = $hash . "." . $file->guessExtension();
}
}
public function getDummyUrl()
{
$object = new UrlService();
$baseUrl = $object->getBaseUrl();
if ($this->getName()) {
return $baseUrl . $this->getUploadDir() . '/' . $this->getName();
}
return $object->getNoImage();
}
/**
* #return mixed
*/
public function getUpdatedAt()
{
return $this->updated_at;
}
/**
* #param mixed $updated_at
*/
public function setUpdatedAt($updated_at)
{
$this->updated_at = $updated_at;
}
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function preUpload()
{
if (null !== $this->getFile()) {
$filename = sha1($this->getFile()->getClientOriginalName());
$this->name = $filename . '.' . $this->getFile()->guessExtension();
}
}
/**
* #ORM\PostPersist()
* #ORM\PostUpdate()
*/
public function upload()
{
if (null === $this->getFile()) {
return;
}
$this->getFile()->move($this->getUploadDir(), $this->name);
$this->file = null;
}
/**
* Lifecycle callback to upload the file to the server
*/
public function lifecycleFileUpload()
{
$this->upload();
}
/**
* #ORM\PreRemove()
*
*
*
*/
public function removeFile()
{
$url = $this->getUploadDir() . '/' . $this->getName();
try {
if (file_exists($url)) {
unlink($url);
}
} catch (\Exception $e) {
return $e->getMessage();
}
}
/**
* Updates the hash value to force the preUpdate and postUpdate events to fire
*/
public function refreshUpdated()
{
$this->setUpdatedAt(new \DateTime());
}
}
And here is a screenshot
enter image description here

symfony2 image multiple upload

I'm trying to figure out how to do multiple file uploads but without luck. I have not been able to get too much info on this.. Maybe someone here will help me out? :D
Criteria:
I know that in my form type I'm supposed to use multiples for fields; but when I add it, it gives me the this error.
Catchable Fatal Error: Argument 1 passed to
PhotoGalleryBundle\Entity\Image::setFile() must be an instance of
Symfony\Component\HttpFoundation\File\UploadedFile, array given,
called in
/home/action/workspace/www/DecorInterior/vendor/symfony/symfony/src/Symfony/Component/PropertyAccess/PropertyAccessor.php
on line 442 and defined
Image Entity
Here is my code in PHP:
<?php
namespace PhotoGalleryBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* Image
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="PhotoGalleryBundle\Entity\ImageRepository")
* #ORM\HasLifecycleCallbacks
*/
class Image
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="imageCaptation", type="string", length=255)
* #Assert\NotBlank
*/
private $imageCaptation;
/**
* #var string
*
* #ORM\Column(name="imageName", type="string", length=255)
*/
private $imageName;
/**
* #var string
*
* #ORM\Column(name="imageFilePath", type="string", length=255, nullable=true)
*/
private $imageFilePath;
/**
* #var \DateTime
*
* #ORM\Column(name="imageUploadedDate", type="datetime")
* #Gedmo\Timestampable(on="create")
*/
private $imageUploadedDate;
/**
* #Assert\File(maxSize="6000000")
*/
private $file;
/**
* #ORM\ManyToOne(targetEntity="Album", inversedBy="images")
* #ORM\JoinColumn(name="album", referencedColumnName="id")
*/
private $album;
private $temp;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set imageCaptation
*
* #param string $imageCaptation
* #return Image
*/
public function setImageCaptation($imageCaptation)
{
$this->imageCaptation = $imageCaptation;
return $this;
}
/**
* Get imageCaptation
*
* #return string
*/
public function getImageCaptation()
{
return $this->imageCaptation;
}
/**
* Set imageName
*
* #param string $imageName
* #return Image
*/
public function setImageName($imageName)
{
$this->imageName = $imageName;
return $this;
}
/**
* Get imageName
*
* #return string
*/
public function getImageName()
{
return $this->imageName;
}
/**
* Set imageFilePath
*
* #param string $imageFilePath
* #return Image
*/
public function setImageFilePath($imageFilePath)
{
$this->imageFilePath = $imageFilePath;
return $this;
}
/**
* Get imageFilePath
*
* #return string
*/
public function getImageFilePath()
{
return $this->imageFilePath;
}
/**
* Get imageUploadedDate
*
* #return \DateTime
*/
public function getImageUploadedDate()
{
return $this->imageUploadedDate;
}
/**
* Set file.
*
* #param UploadedFile $file
*/
public function setFile(UploadedFile $file = null) {
$this->file = $file;
// check if we have an old image path
if (isset($this->imageFilePath)) {
// store the old name to delete after the update
$this->temp = $this->imageFilePath;
$this->imageFilePath = null;
} else {
$this->imageFilePath = 'initial';
}
}
/**
* #ORM\PrePersist()
* #ORM\PreUpdate
*/
public function preUpload() {
if (null !== $this->getFile()) {
// do whatever you want to generate a unique name
$fileName = sha1(uniqid(mt_rand(), true));
$this->imageFilePath = $fileName . '.' . $this->getFile()->guessExtension();
}
}
/**
* #ORM\PostPersist()
* #ORM\PostUpdate
*/
public function upload() {
if (null === $this->getFile()) {
return;
}
// if there is an error when moving the file, an exception will
// be automatically thrown by move(). This will properly prevent
// the entity from being persisted to the database on error
$this->getFile()->move($this->getUploadRootDir(), $this->imageFilePath);
// check if we have an old image
if (isset($this->temp)) {
// delete the old image
unlink($this->getUploadRootDir() . '/' . $this->temp);
// clear the temp image path
$this->temp = null;
}
$this->imageFilePath = null;
}
/**
* #ORM\PostRemove()
*/
public function removeUpload() {
$file = $this->getAbsolutePath();
if ($file) {
unlink($file);
}
}
/**
* Get file.
*
* #return UploadedFile
*/
public function getFile() {
return $this->file;
}
public function getAbsolutePath() {
return null === $this->imageFilePath
? null
: $this->getUploadRootDir() . '/' . $this->imageFilePath;
}
public function getWebPath() {
return null === $this->imageFilePath
? null
: $this->getUploadDir() . '/' . $this->imageFilePath;
}
public function getUploadRootDir() {
// the absolute path where uploaded
// documents should be saved
return __DIR__.'/../../../web/' . $this->getUploadDir();
}
public function getUploadDir() {
// get rid of the __DIR__ so it doesn't screw up
// when displaying uploaded doc/image in the view
return 'uploads/images';
}
/**
* Set album
*
* #param \PhotoGalleryBundle\Entity\Album $album
* #return Image
*/
public function setAlbum(\PhotoGalleryBundle\Entity\Album $album = null)
{
$this->album = $album;
return $this;
}
/**
* Get album
*
* #return \PhotoGalleryBundle\Entity\Album
*/
public function getAlbum()
{
return $this->album;
}
}
ImageType:
<?php
namespace PhotoGalleryBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class ImageType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('imageCaptation')
->add('imageName')
->add('file', 'file', array('multiple' => TRUE))
->add('album')
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'PhotoGalleryBundle\Entity\Image'
));
}
/**
* #return string
*/
public function getName()
{
return 'photogallerybundle_image';
}
}
In this case the value will be an array of UploadedFile objects. Given that you have a type with multiple files yet only one caption, name, etc I assume you will want to refactor Image to support multiple image files. In this case the file property would be better known as files and setFiles should accept an array.
If however you want have one Image entity per file uploaded, consider implementing a collection instead.
Alternatively you could manually process the form in your action. For example:
public function uploadAction(Request $request)
{
foreach ($request->files as $uploadedFile) {
$uploadedFile = current($uploadedFile['file']);
// Build Image using each uploaded file
}
...

PHP post request stopped with blank page

I've got a form with embedded file form (News and NewsFiles collection). On my localhost machine everything works fine: News and NewsFiles entities persists, files are uploaded.
But on production server post request is stopped when I try add file. Files are uploaded, entities don't exist in db, post request is stopped with status: 302 Found and it returns blank page instead of redirect to next page.
public function createAction(Request $request) {
$entity = new News();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
// PROBLEM APPEARS HERE - WHEN TRY TO FLUSH
$em->flush();
$this->get('session')->getFlashBag()->add(
'success', 'Wykonano pomyślnie!'
);
return $this->redirect($this->generateUrl('website_admin_panel_news'));
}
return $this->render('WebsiteNewsBundle:News:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
There is no problem when I try to add only News entity (without files). The same is when I am editing entity.
LOGS:
logs
INFO - Matched route "news_update" (parameters: "_controller": "Website\NewsBundle\Controller\NewsController::updateAction", "id": "6", "_route": "news_update")
DEBUG - Read SecurityContext from the session
DEBUG - Reloading user from user provider.
DEBUG - Username "admin" was reloaded from user provider.
DEBUG - Write SecurityContext in the session
I think the problem is on the server side, I will write to the administrator but he isn't an expert so I need to suggest him what he has to change... Any ideas? May it be a problem of timeouts?
Edit:
I've got more information. The problem occurs in move() function. It's not a problem with timeouts because I've tried to send little file (1px - 539 byte) and it still doesn't do the job.
Here is my Entity to upload:
<?php
namespace Website\NewsBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
// use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Validator\Constraints;
/**
*
*
* #ORM\Entity
* #ORM\HasLifecycleCallbacks
* #ORM\Table(name="NewsFiles")
*
*/
class NewsFile {
private $temp;
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*
*/
private $owner;
/**
*
*/
private $file;
/**
* #ORM\Column(type="string", length=255)
*
*/
private $name;
/**
* #ORM\Column(type="datetime")
*/
private $created_at;
/**
* #ORM\ManyToOne(targetEntity="News", inversedBy="newsFiles")
* #ORM\JoinColumn(name="news_id", referencedColumnName="id")
*/
protected $news;
/**
* #var string
*
* #ORM\Column(name="path", type="string", length=255)
*/
private $path;
/**
* #var string
*
* #ORM\Column(type="boolean", nullable=false)
*/
private $isMain;
/**
* Now we tell doctrine that before we persist or update we call the updatedTimestamps() function.
*
* #ORM\PrePersist
* #ORM\PreUpdate
*/
public function updatedTimestamps() {
if ($this->getCreated_At() == null) {
$this->setCreated_At(new \DateTime(date('Y-m-d H:i:s')));
}
}
public function setId($id) {
$this->id = $id;
}
public function getId() {
return $this->id;
}
public function setOwner($owner) {
$this->owner = $owner;
}
public function getOwner() {
return $this->owner;
}
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function setPath($path) {
$this->path = $path;
}
public function getPath() {
return $this->path;
}
/**
* Set created_at
*
* #param string $created_at
* #return File
*/
public function setCreated_at($created_at) {
$this->created_at = $created_at;
return $this;
}
/**
* Get created_at
*
* #return string
*/
public function getCreated_at() {
return $this->created_at;
}
/**
* Sets file.
*
* #param UploadedFile $file
*/
public function setFile(UploadedFile $file = null) {
$this->file = $file;
// check if we have an old image path
if (isset($this->path)) {
// store the old name to delete after the update
$this->temp = $this->path;
$this->path = null;
} else {
$this->path = 'initial';
}
}
/**
* Get file.
*
* #return UploadedFile
*/
public function getFile() {
return $this->file;
}
public function getAbsolutePath() {
return null === $this->path ? null : $this->getUploadRootDir() . '/' . $this->path;
}
public function getWebPath() {
return null === $this->path ? null : $this->getUploadDir() . '/' . $this->path;
}
protected function getUploadRootDir() {
// the absolute directory path where uploaded documents should be saved
return __DIR__ . '/../../../../web/' . $this->getUploadDir();
}
protected function getUploadDir() {
return 'uploads/News/' . $this->getNews()->getId();
}
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function preUpload() {
if (null !== $this->file) {
// zrób cokolwiek chcesz aby wygenerować unikalną nazwę
$this->setName(sha1(uniqid(mt_rand(), true)));
$this->setPath($this->getName() . '.' . $this->file->guessExtension());
}
}
/**
* #ORM\PostPersist()
* #ORM\PostUpdate()
*/
public function upload() {
// zmienna file może być pusta jeśli pole nie jest wymagane
if (null === $this->file) {
return;
}
// HERE HE CANCEL HIS WORK
$this->getFile()->move($this->getUploadRootDir(), $this->path);
// check if we have an old image
if (isset($this->temp)) {
echo "isset temp";
// delete the old image
unlink($this->getUploadRootDir() . '/' . $this->temp);
// clear the temp image path
$this->temp = null;
}
$this->file = null;
}
/**
* #ORM\PostRemove()
*/
public function removeUpload() {
if ($file = $this->getAbsolutePath()) {
unlink($file);
}
}
/**
* Set news
*
* #param string $news
* #return News
*/
public function setNews($news) {
$this->news = $news;
return $this;
}
/**
* Get news
*
* #return string
*/
public function getNews() {
return $this->news;
}
/**
* Set isMain
*
* #param string $isMain
* #return IsMain
*/
public function setIsMain($isMain) {
$this->isMain = $isMain;
return $this;
}
/**
* Get isMain
*
* #return string
*/
public function getIsMain() {
return $this->isMain;
}
}
Ok, I've discovered what's going on.
My prod server doesn't accept chmod function, it is locked. The Symfony2 file:
/vendor/symfony/symfony/src/Symfony/Component/HttpFoundation/File/UploadedFile.php
has move() function -> I've deleted chmod usage there and everythning works fine.
Here is move() function after modification:
public function move($directory, $name = null)
{
if ($this->isValid()) {
if ($this->test) {
return parent::move($directory, $name);
}
$target = $this->getTargetFile($directory, $name);
if (!#move_uploaded_file($this->getPathname(), $target)) {
$error = error_get_last();
throw new FileException(sprintf('Could not move the file "%s" to "%s" (%s)', $this->getPathname(), $target, strip_tags($error['message'])));
}
return $target;
}
throw new FileException($this->getErrorMessage());
}

Catchable Fatal Error: Argument 1 passed to ? Symfony2.1

I am stopped by this error:
Catchable Fatal Error: Argument 1 passed to
Joker\CoreBundle\Entity\Incidentfile::setFile() must be an instance of
Symfony\Component\HttpFoundation\File\UploadedFile, string given,
called in
/Applications/MAMP/htdocs/joker-repo/vendor/symfony/symfony/src/Symfony/Component/Form/Util/PropertyPath.php
on line 538 and defined in
/Applications/MAMP/htdocs/joker-repo/src/Joker/CoreBundle/Entity/Incidentfile.php
line 157
In my entity I have setters and getters for File. I used this method to make file Upload: THIS
And there was permission problem for folder upload_images but after i solved it everything worked fine but now something went wrong.
Here is entity
/**
* Incidentfile
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Joker\CoreBundle\Entity\IncidentfileRepository")
* #ORM\HasLifecycleCallbacks
*/
class Incidentfile
{
//
// /**
// * #ORM\ManyToOne(targetEntity="Incidentlist", inversedBy="ListFiles")
// * #ORM\JoinColumn(name="IncidentListId", referencedColumnName="id")
// */
// protected $FileList;
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var \DateTime
*
* #ORM\Column(name="createdat", type="datetime")
*/
private $createdat;
/**
* Image path
*
* #var string
*
* #ORM\Column(type="text", length=255, nullable=false)
*/
protected $path;
/**
* Image file
*
* #var File
*
* #Assert\File(
* maxSize = "5M",
* mimeTypes = {"image/jpeg", "image/gif", "image/png", "image/tiff"},
* maxSizeMessage = "The maxmimum allowed file size is 5MB.",
* mimeTypesMessage = "Only the filetypes image are allowed."
* )
*/
protected $file;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set createdat
*
* #param \DateTime $createdat
* #return Incidentfile
*/
public function setCreatedat($createdat)
{
$this->createdat = $createdat;
return $this;
}
/**
* Get createdat
*
* #return \DateTime
*/
public function getCreatedat()
{
return $this->createdat;
}
/**
* 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);
}
}
public function getWebPath()
{
return null === $this->path
? null
: $this->getUploadDir().'/'.$this->path;
}
/**
* Called after entity persistence
*
* #ORM\PostPersist()
* #ORM\PostUpdate()
*/
protected function getUploadRootDir()
{
// the absolute directory path where uploaded
// documents should be saved
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 'uploaded_images';
}
/**
* Sets file.
*
* #param UploadedFile $file
*/
public function setFile(UploadedFile $file = null)
{ if (null === $file) {
return;
}
$this->file = $file;
if(in_array($file->getMimeType(),array("image/jpeg", "image/gif", "image/png", "image/tiff"))){
$filename=rand(100000,1000000).'_'.$file->getClientOriginalName();
$file->move($this->getUploadRootDir(),$filename
);
$this->path =$filename;
$this->file = null;
}
else $this->path=null;
}
/**
* Get file.
*
* #return UploadedFile
*/
public function getFile()
{
return $this->file;
}
public function upload() {
// the file property can be empty if the field is not required
if (null === $this->getFile()) {
return;
}
$file=$this->getFile();
$filename=rand(100000,1000000).'_'.$file->getClientOriginalName();
// we use the original file name here but you should
// sanitize it at least to avoid any security issues
// move takes the target directory and target filename as params
$file->move($this->getUploadRootDir(),$filename
);
// set the path property to the filename where you've saved the file
$this->path =$filename;
// clean up the file property as you won't need it anymore
$this->setFile(null);
}
/**
* Set path
*
* #param string $path
* #return Incidentfile
*/
public function setPath($path)
{
$this->path = $path;
return $this;
}
/**
* Get path
*
* #return string
*/
public function getPath()
{
return $this->path;
}
/**
* Set FileList
*
* #param \Joker\CoreBundle\Entity\Incidentlist $fileList
* #return Incidentfile
*/
public function setFileList(\Joker\CoreBundle\Entity\Incidentlist $fileList = null)
{
$this->FileList = $fileList;
return $this;
}
/**
* Get FileList
*
* #return \Joker\CoreBundle\Entity\Incidentlist
*/
public function getFileList()
{
return $this->FileList;
}
}
And here is my controler:
public function TestAction(Request $request){
$incfileRepo = new Incidentfile();
$formfile = $this->createForm(new IncfileType(), $incfileRepo);
if ($request->isMethod('POST')) {
$formfile->bind($request);
if ($formfile->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($incfileRepo);
$em->flush();
return $this->redirect($this->generateUrl('incident_show'));
}
}
$spotEntity = $this->getCurrentSpot();
$sentryEntity = $this->getCurrentSentry();
$messagesCollection = $this->getDoctrine()->getRepository('JokerCoreBundle:Message')->findBy(array(
'spot' => $spotEntity,
'sentry' => $sentryEntity
), array(
'sent_date' => 'DESC'
));
return $this->render('JokerAdminBundle:incidents:addfullform.html.twig', $this->getViewConstants(array(
'formfile'=>$formfile->createView(),
'spot' => $spotEntity,
'sentry' => $sentryEntity,
'messagesCollection' => $messagesCollection,
)));
}
Form in twig:
<form action="" method="post">
{{ form_rest(formfile) }}
<div class="singleTableForm">
<input style="float: left; margin-left: 338px; " type="submit" name="" class="button" value="Add" />
</div>
</form>
I found out what was wrong.. In twig was problem:
<form action="" method="post" {{ form_enctype(formfile) }}>
Just add **{{ form_enctype(formfile) }}**
You must add annotation
/**
* #ORM\PostPersist()
* #ORM\PostUpdate()
*/
public function upload()
see more http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html
And show the form code
UPD: best way - use tags {{ form_start(form) }} and {{ form_end(form) }} it will also protect you from csrf attacks

How to download an uploaded file in symfony 2?

I have a Document Entity and I want that the user of the website be able to download the files that have been uploaded.
I don't know how to do this (I tried with a downloadAction in my DocumentController but I have some errors).
Here is my Document entity :
<?php
namespace MyBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints as DoctrineAssert;
use Symfony\Component\HttpFoundation\File\UploadedFile;
/**
* MyBundle\Entity\Document
* #ORM\Table()
* #ORM\Entity()
* #ORM\HasLifecycleCallbacks
*/
class Document
{
public function __toString() {
return $this->document_type->getName();
}
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var date $endDate
*
* #ORM\Column(name="endDate", type="date")
*/
private $endDate;
/**
* #ORM\ManyToOne(targetEntity="DocumentType")
* #ORM\JoinColumn(name="document_type_id", referencedColumnName="id")
*/
private $document_type;
/**
* #ORM\Column(type="string", length="255", nullable="TRUE")
* #Assert\File(maxSize="6000000")
*/
public $file;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
public $path;
public function getAbsolutePath()
{
return null === $this->path ? null : $this->getUploadRootDir().'/'.$this->path;
}
public function getWebPath()
{
return null === $this->path ? null : $this->getUploadDir().'/'.$this->path;
}
protected function getUploadRootDir()
{
// the absolute directory path where uploaded documents should be saved
return __DIR__.'/../../../../web/'.$this->getUploadDir();
}
protected function getUploadDir()
{
// get rid of the __DIR__ so it doesn't screw when displaying uploaded doc/image in the view.
return 'uploads/documents';
}
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function preUpload()
{
if (null !== $this->file) {
// do whatever you want to generate a unique name
$this->path = uniqid().'.'.$this->file->guessExtension();
}
}
/**
* #ORM\PostPersist()
* #ORM\PostUpdate()
*/
public function upload()
{
if (null === $this->file) {
return;
}
$this->file->move($this->getUploadRootDir(), $this->path);
unset($this->file);
}
/**
* #ORM\PostRemove()
*/
public function removeUpload()
{
if ($file = $this->getAbsolutePath()) {
unlink($file);
}
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set endDate
*
* #param date $endDate
*/
public function setEndDate($endDate)
{
$this->endDate = $endDate;
}
/**
* Get endDate
*
* #return endDate
*/
public function getEndDate()
{
return $this->endDate;
}
/**
* Set document_type
*
* #param Was\RHBundle\Entity\DocumentType $documentType
*/
public function setDocumentType(MyBundle\Entity\DocumentType $documentType)
{
$this->document_type = $documentType;
}
/**
* Get document_type
*
* #return MyBundle\Entity\DocumentType
*/
public function getDocumentType()
{
return $this->document_type;
}
/**
* Set path
*
* #param string $path
*/
public function setPath($path)
{
$this->path = $path;
}
/**
* Get path
*
* #return string
*/
public function getPath()
{
return $this->path;
}
/**
* Set file
*
* #param string $file
*/
public function setFile($file)
{
$this->file = $file;
}
/**
* Get file
*
* #return string
*/
public function getFile()
{
return $this->file;
}
}
Now, here is my downloadAction in my DocumentController.php :
public function downloadAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
$document = $em->getRepository('MyBundle:Document')->find($id);
if (!$document) {
throw $this->createNotFoundException('Unable to find the document');
}
$headers = array(
'Content-Type' => $document->getMimeType()
'Content-Disposition' => 'attachment; filename="'.$document->getDocumentType().'"'
);
$filename = $document->getUploadRootDir().'/'.$document->getDocumentType();
return new Response(file_get_contents($filename), 200, $headers);
}
I've got this error :
Call to undefined method MyBundle\Entity\Document::getMimeType()
I use IgorwFileServeBundle.
Here a sample I used on one of my project :
$em = $this->getDoctrine()->getEntityManager();
$file = $em->getRepository('MyBundle:File')->find($id);
$path = $file->getPath();
$mimeType = $file->getMimeType();
$folder = 'Public';
$factory = $this->get('igorw_file_serve.response_factory');
$response = $factory->create($folder.'/'.$path, $mimeType);
return $response;
I hope it can help
Here is the code from one of my project
public function downloadAction()
{
$items = $this->get('xxxx')->getXXX();
$response = $this->render('xxx:xxx:xxx.csv.twig', array('items' => $items));
$response->headers->set('Content-Type', 'text/csv');
$response->headers->set('Content-Disposition', 'attachment; filename=budget.csv');
return $response;
}
Add variable $mimeType to the Document entity
/**
* #ORM\Column()
* #Assert\NotBlank
*/
private $mimeType;
and getters and setters (or generate them)
public function setMimeType($mimeType) {
$this->mimeType = $mimeType;
return $this;
}
public function getMimeType() {
return $this->mimeType;
}
update the database schema
php app/console doctrine:schema:update --force
and add setMimeType to your setFile function
/**
* Set file
*
* #param string $file
*/
public function setFile($file)
{
$this->file = $file;
$this->setMimeType($this->getFile()->getMimeType());
}
Then your controller will work properly.

Categories