Search code examples
symfonyfosrestbundlepostmanvichuploaderbundle

Handle imageupload using symfony2 + VichUploaderBundle + FOSRestBundle, Testing with Postman (chrome extension)


I am trying to implement image uploads to my Symfony2 Rest server. I used VichUploaderBundle to handle this. I followed the instructions posted here.

So I basically added the following to my Post.php (Entity that I want to attach an image to)

/**
 * NOTE: This is not a mapped field of entity metadata, just a simple property.
 * 
 * @Vich\UploadableField(mapping="product_image", fileNameProperty="imageName")
 * 
 * @var File $imageFile
 */
protected $imageFile;

/**
 * @ORM\Column(type="string", length=255, name="image_name")
 *
 * @var string $imageName
 */
protected $imageName;

/**
 * @ORM\Column(type="datetime")
 *
 * @var \DateTime $updatedAt
 */
protected $updatedAt;





/**
 * If manually uploading a file (i.e. not using Symfony Form) ensure an instance
 * of 'UploadedFile' is injected into this setter to trigger the  update. If this
 * bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
 * must be able to accept an instance of 'File' as the bundle will inject one here
 * during Doctrine hydration.
 *
 * @param File|\Symfony\Component\HttpFoundation\File\UploadedFile $image
 */
public function setImageFile(File $image = null)
{
    $this->imageFile = $image;

    if ($image) {
        // It is required that at least one field changes if you are using doctrine
        // otherwise the event listeners won't be called and the file is lost
        $this->updatedAt = new \DateTime('now');
    }
}

/**
 * @return File
 */
public function getImageFile()
{
    return $this->imageFile;
}

/**
 * @param string $imageName
 */
public function setImageName($imageName)
{
    $this->imageName = $imageName;
}

Added the following to my config.yml

vich_uploader:
    db_driver: orm
    mappings:
        product_image:
            uri_prefix:         /images/products
            upload_destination: %kernel.root_dir%/../web/images/products

Added this line to PostType.php

->add('imagefile', 'file')

I'm trying now to test if this functionality is working. As this is a Rest API I'm using Postman (Chrome extension) to try and POST a new post. Here's what I'm trying to send along with the error received

enter image description here

PS: I have intentionally left out the header field as Content-Type application/json gave a bad request error.


Solution

  • Working form

    The problem was on the server side though. I shouldn't have added ->add('imagefile', 'file') to the PostType.php, instead, I added it in ther controller as $form = $this->createForm(new PostType(), $entity, array("method" => $request->getMethod()))->add('imageFile','file');