I have a form in which I have a file
field to upload an image. I need to upload this image on Amazon S3. Building this step by step I started to upload the image on the local disk and it's now working.
The upload is occurring inside my entity Page
as it's recommended to test the success of the upload before to save the entity. I ended up with this chunk of code
/**
* @ORM\Column(name="objectThumbnail", type="string", length=255, nullable=true)
*/
protected $objectThumbnail;
/**
* This is not a column in the database but it's mapping a field from the form
*
* @Assert\File(maxSize="600000000")
*/
public $file;
...
/**
* @ORM\PrePersist()
* @ORM\PreUpdate()
*/
public function preUpload()
{
if (null !== $this->file) {
// generate a unique filename
$this->objectThumbnail = $this->getGuid().'.'.$this->file->guessExtension();
}
}
/**
* @ORM\PostPersist()
* @ORM\PostUpdate()
*/
public function upload()
{
if (null === $this->file) {
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->file->move($this->getUploadRootDir(), $this->objectThumbnail);
unset($this->file);
}
/**
* @ORM\PostRemove()
*/
public function removeUpload()
{
if ($file = $this->getAbsolutePath()) {
unlink($file);
}
}
That's perfect, it's working like a charm.
Just Symfony (2.1.7) screaming because of the public scope of the file
attribute, nothing major.
Now I need to integrate the S3 layer. For that I think I'll be using Gaufrette
and StreamWrapper
.
Now I'm struggling to find what is the best way to do it. How do I get access to the Filesystem
service in the Entity? Is it really clean to do it like this? It feels a bit awkward to me to process the upload of the image on S3 in the Entity.
How would you recommend to do it ?
Cheers,
Maxime
using service in your entity is not a good pratice. I would recommand to create a form handler that performs validation, persistance and upload in this example
i wrote an example that fits your needs
The handler class
Hope this helped
Maybe you should check VichUploaderBundle which basically inject File object into your entites and integration with Gaufrette is quite easy.