файл больше не сохраняется, vichuploader

Я на самом деле создаю API. Я использую vichuploaderBundler для импорта файлов и помещения их в определенный каталог. Поскольку я использую свою форму для отправки запроса POST для создания ресурса, мой ресурс создается, но файлы больше не сохраняются. Вот мой текущий код.

postController

/**
* @Rest\View(statusCode=Response::HTTP_CREATED)
* @Rest\Post("/posts")
*/
public function postPostsAction(Request $request)
{
$post = new Post();
$form = $this->createForm(PostType::class, $post);
$form->submit($request->request->all()); // Validation des données

if ($form->isValid()) {
$post->setUpdatedAt(new \DateTime());
$em = $this->get('doctrine.orm.entity_manager');
$em->persist($post);
$em->flush();
return $post;
} else {
return $form;
}
}

PostType

class PostType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('title');
$builder->add('description');
$builder->add('imageName');
$builder->add('imageFile', FileType::class);
}

/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Post',
//An API must be stateless, Cross-Site Request Forgery must be disable
'csrf_protection' => false,
));
}

/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return 'appbundle_post';
}}

Почтовая организация:

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\File;
use JMS\Serializer\Annotation\ExclusionPolicy;
use JMS\Serializer\Annotation\Expose;
use JMS\Serializer\Annotation\Groups;
use JMS\Serializer\Annotation\VirtualProperty;
use Vich\UploaderBundle\Mapping\Annotation as Vich;

/**
* Post
* @ORM\Entity(repositoryClass="AppBundle\Repository\PostRepository")
* @ExclusionPolicy("all")
* @Vich\Uploadable
*/
class Post
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
* @Expose
*/
private $id;

/**
* @var string
*
* @ORM\Column(name="Title", type="string", length=100)
*/
private $title;

/**
* @var string
* @Expose
* @ORM\Column(name="Description", type="string", length=400, nullable=true)
*/
private $description;

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

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

/**
* NOTE: This is not a mapped field of entity metadata, just a simple property.
*
* @Vich\UploadableField(mapping="product_image", fileNameProperty="imageName")
* @var File
*/
private $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
* @Expose
* @return Post
*/
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;
}

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

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

return $this;
}

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

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

/**
* Set title
*
* @param string $title
*
* @return Post
*/
public function setTitle($title)
{
$this->title = $title;

return $this;
}

/**
* Get title
*
* @return string
*/
public function getTitle()
{
return $this->title;
}

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

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

/**
* Set description
*
* @param string $description
*
* @return Post
*/
public function setDescription($description)
{
$this->description = $description;

return $this;
}

/**
* Get description
*
* @return string
*/
public function getDescription()
{
return $this->description;
}

}

РЕДАКТИРОВАТЬ :

Вот моя конфигурация vichuploader, в config.yml

#vich uploader Configuration
vich_uploader:
db_driver: orm
mappings:
product_image:
uri_prefix:         /images/posts
upload_destination: '%kernel.root_dir%/../web/images/posts'
namer:              vich_uploader.namer_uniqid

inject_on_load:     false
delete_on_update:   true
delete_on_remove:   true

Перед использованием формы я загружал таким образом:

 public function postPostsAction(Request $request)
{
$post = new Post();
$post->setTitle($request->get('title'))
->setDescription($request->get('description'))
->setImageName($request->get('image_name'))
->setImageFile($request->files->get('imageFile'))
// 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
->setUpdatedAt(new \DateTime());// On fait appel à doctrine pour seter un id lors de la création en base
$em = $this->get('doctrine.orm.entity_manager');
$em->persist($post);
$em->flush();

return $post;
}

Спасибо за помощь !

1

Решение

Задача ещё не решена.

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector