title: Symfony 2 - Best practice to upload an image on Amazon S3
body: <p>I have a form in which I have a <code>file</code> 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. </p>
  
  <p>The upload is occurring inside my entity <code>Page</code> as it's recommended to test the success of the upload before to save the entity. I ended up with this chunk of code</p>
  
  <pre><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-&gt;file) {
              // generate a unique filename
              $this-&gt;objectThumbnail = $this-&gt;getGuid().'.'.$this-&gt;file-&gt;guessExtension();
          }
      }
  
      /**
       * @ORM\PostPersist()
       * @ORM\PostUpdate()
       */
      public function upload()
      {
          if (null === $this-&gt;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-&gt;file-&gt;move($this-&gt;getUploadRootDir(), $this-&gt;objectThumbnail);
  
          unset($this-&gt;file);
      }
  
      /**
       * @ORM\PostRemove()
       */
      public function removeUpload()
      {
          if ($file = $this-&gt;getAbsolutePath()) {
              unlink($file);
          }
      }
  </code></pre>
  
  <p>That's perfect, it's working like a charm.
  Just Symfony (2.1.7) screaming because of the public scope of the <code>file</code> attribute, nothing major.</p>
  
  <p>Now I need to integrate the S3 layer. For that I think I'll be using <code>Gaufrette</code> and <code>StreamWrapper</code>. </p>
  
  <p>Now I'm struggling to find what is the best way to do it. How do I get access to the <code>Filesystem</code> 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. </p>
  
  <p>How would you recommend to do it ?</p>
  
  <p>Cheers, </p>
  
  <p>Maxime</p>