5

A basic Symfony 3 application has the VichUploader bundle installed and configured, with an entity for uploading files against.

How do I attach a file to this entity in my ORM data fixtures?


There is a question for this problem in Symfony 2 and I have tried that code. The fixtures load without error, but the "uploaded" file is not copied to its final destination.

I can do this manually, my latest attempt looks like this:

<?php
// src/AppBundle/DataFixtures/ORM/LoadCourseData.php

namespace AppBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesser;
use AppBundle\Entity\Course;

class LoadCourseData extends AbstractFixture implements OrderedFixtureInterface
{
    public function load(ObjectManager $manager)
    {
        $course = new Course();
        $course->setName('How to make data fixtures in Symfony lol')
            ->setAuthor($this->getReference('admin-user'))
            ->setSummary('You\'ll know when I know!')
            ->setLicense($this->getReference('cc-by'))
            ->setDifficulty(1);

        // Persist to generate slug (to be used for uploads)
        $manager->persist($course);

        // Attach file

        // I copy it to a temporary directory as per the Symfony2 answer
        copy(__DIR__.'/../Files/kitten.jpg', '/tmp/kitten.jpg');

        // These are filled in for completeness
        $mimetype = MimeTypeGuesser::getInstance()->guess('/tmp/kitten.jpg');
        $size     = filesize('/tmp/kitten.jpg');

        // Create a new UploadedFile
        $file = new UploadedFile('/tmp/kitten.jpg', 'kitten.jpg', $mimetype, $size, null, true);

        // I have to move it manually?
        // Plus how can I take advantage of the VichUploader namer?
        $file->move(__DIR__.'/../../../../web/img/upload/course/');

        // Apply to entity
        $course->setImageFile($file);

        // Persist
        $manager->persist($course);
        $manager->flush();
    }

    public function getOrder()
    {
        return 4;
    }
}

My solution still needs a lot of work! Am I barking up the wrong tree?

  • The upload paths are already defined in config.yml. I should access them from there or convert them to parameters
  • Needs a lot more error checking and exception throwing
  • The file is copied to the destination but the filename is wrong, because it's not using the configured VichUploader namer
  • It should live somewhere else, probably as a service?

1 Answer 1

0

I found the VichUploader documentation on GitHub not very good, so I suggest you use the Symfony documentation: http://symfony.com/doc/current/controller/upload_file.html

I created a FileUploader.php under src/AppBundle like so:

<?php

// src/AppBundle/FileUploader.php
namespace AppBundle;

use Symfony\Component\HttpFoundation\File\UploadedFile;

class FileUploader
{
    private $targetDir;

    public function __construct($targetDir)
    {
        $this->targetDir = $targetDir;
    }

    public function upload(UploadedFile $file, $path, $name)
    {
        $fileName = $name.'.'.$file->guessExtension();

        $file->move($this->targetDir.$path, $fileName);

        return $fileName;
    }
}

This allows you to specify the File, the path and name.

Then in your app/config/service.yml file, add this to reference it:

services:
  app.attachment_uploader:
      class: AppBundle\FileUploader
      arguments: ['%document_directory%']

Then you need to specify the %document_directory% in your app/config/parameters.yml file:

parameters:
...
    document_directory: documents

In my case, the above 'documents' folder lives under the web folder, so the path is 'web/documents'. I wanted to store everything in the same location.

Then I use the FileUploader in any controller like so:

...
->add('catalog', FileType::class, array(            // Docs
        'label' => 'Catalog Course Description ',
        'required' => false,
        'attr' => array(
                'accept' => 'image/*,application/pdf,text/plain,application/msword',
                'onchange' => "checkFileSize('form_catalog')"
        ),
))
...

$file = $form->get("catalog")->getData();
$fileName = $this->get('app.attachment_uploader')->upload( $file,
        '/'.$pet->getStudent()->getBanId(),
        $pet->getCourse()->getCorTitle().'_'.'Catalog_Course_Desc'
...

$att_cat->setDocument($fileName);
$em->persist($att_cat);
$em->flush();

Where in the above code, I'm getting the "catalog" file button data, which is the file. Then call the 'upload' method specifying the file and path and filename parameters. Then later persist the Entity ($att_cat).

The above is very simple to use.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.