загрузка не выполняется с помощью VichUploaderBundle

Я хотел бы использовать VichUploaderBundle для загрузки файлов в мой проект symfony 3.2.3 (PHP 5.6). Я много чего пробую, но ничего не загружаю. Но уровень устойчивости отлично работает с моей базой данных.

config.yml

knp_gaufrette:
    stream_wrapper: ~

    adapters:
        fileupload_adapter:
            local:
                directory: %kernel.root_dir%/../web/
                create: true

    filesystems:
        fileupload_fs:
            adapter:    fileupload_adapter

# VichUploaderBundle Configuration
vich_uploader:
    db_driver: orm
    twig: true
    storage: gaufrette
    mappings:
        tgmedia_file:
            uri_prefix: web
            upload_destination: fileupload_fs
            namer: vich_uploader.namer_origname

Сущность

namespace MediaBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use TweedeGolf\MediaBundle\Model\AbstractFile;
use Vich\UploaderBundle\Mapping\Annotation as Vich;

/**
 * @ORM\Entity
 * @Vich\Uploadable
 * @ORM\HasLifecycleCallbacks
 * @ORM\Table
 */
class FileUpload
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

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

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

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

    /**
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

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

    /**
     * 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
     *
     * @return Product
     */
    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 \DateTimeImmutable();
        }

        return $this;
    }

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

        return $this;
    }

    /**
     * @return string|null
     */
    public function getImageName()
    {
        return $this->imageName;
    }

    /**
     * Set updatedAt
     *
     * @param \DateTime $updatedAt
     *
     * @return FileUpload
     */
    public function setUpdatedAt($updatedAt)
    {
        $this->updatedAt = $updatedAt;

        return $this;
    }

    /**
     * Get updatedAt
     *
     * @return \DateTime
     */
    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }
}

Тип формы

<?php

namespace MediaBundle\Form;

use MediaBundle\Entity\File;
use MediaBundle\Entity\FileUpload;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Vich\UploaderBundle\Form\Type\VichFileType;
use Vich\UploaderBundle\Form\Type\VichImageType;

class FileUploadType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('imageName')
            ->add('imageFile', VichImageType::class, [
                'required' => false,
                'allow_delete' => true,
                'download_link' => true,
                'mapped' => false,
                'data_class' => null
            ])
            ->add('submit', SubmitType::class);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => FileUpload::class,
            'csrf_protection' => false,
        ));
    }
}

Контроллер

<?php

namespace MediaBundle\Controller;

use MediaBundle\Entity\File;
use MediaBundle\Entity\FileUpload;
use MediaBundle\Entity\Product;
use MediaBundle\Form\FileType;
use MediaBundle\Form\FileUploadType;
use MediaBundle\Form\ProductType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

class MainController extends Controller
{
    public function indexAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();

        $fileUploaded = new FileUpload();

        $form = $this->createForm(FileUploadType::class, $fileUploaded, array(
            'action' => $this->generateUrl('media_main')
        ));

        $form->handleRequest($request);

        if ($form->isSubmitted())
        {
            $fileUploaded->setUpdatedAt(new \DateTime());
            $fileUploaded->setImageFile($form->get('imageFile')->getData());
            $em->persist($fileUploaded);
            $em->flush();
        }

        return $this->render('MediaBundle:main:index.html.twig', array(
            'form' => $form->createView()
        ));
    }
}

Где моя ошибка? Что не так ?


person darkomen    schedule 24.02.2017    source источник


Ответы (1)


    uri_prefix:         /project/web/fileupload_fs
    upload_destination: '%kernel.root_dir%/../web/fileupload_fs'

uri_prefix начинается с папки www.

и измените контроллер таким образом

if ($form->isSubmitted() && $form->isValid())
{

    $em->persist($fileUploaded);
    $em->flush();
}
person walidtlili    schedule 25.02.2017