I made the decision below. You can adapt it to your needs. But you need an additional command that clears old files in the uploads / tmp directory. And you need two parameters in the parameters section in config:
parameters: uploads_dir: %kernel.root_dir%/../web/uploads uploads_tmp_dir: %uploads_dir%/tmp
The form:
public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('file',ImageFileType::TYPE_NAME,array( 'fileField' => 'file', 'pathField' => 'path', 'required' => false, 'label' => 'makeswapping.form.single_image', 'imgclass' => 'tumbnail imgbox full-width', 'constraints' => array( new Assert\Image(array( 'minWidth' => '440' )) ) )); $container = $this->container; $builder->addEventListener( FormEvents::PRE_SUBMIT, function (FormEvent $event) use ($container) { $form = $event->getForm(); $data = $event->getData(); $uploadsTmpDir = $container->getParameter('uploads_tmp_dir'); if (isset($data['file'])) { $filename = sprintf('%s.%s', uniqid('tmp_'), $data['file']->getClientOriginalExtension()); if (!file_exists($uploadsTmpDir)) { mkdir($uploadsTmpDir, 0755, true); } copy($data['file']->getRealPath(), $uploadsTmpDir . '/' . $filename); $form->add('file_hidden', 'hidden', array( 'mapped' => false, 'required' => false, 'empty_data' => $filename, )); } else if (!isset($data['file']) && isset($data['file_hidden'])) { $fileInfo = new \SplFileInfo($uploadsTmpDir . '/' . $data['file_hidden']); $mimeTypeGuesser = MimeTypeGuesser::getInstance(); $uploadedFile = new UploadedFile( $fileInfo->getRealPath(), $fileInfo->getBasename(), $mimeTypeGuesser->guess($fileInfo->getRealPath()), $fileInfo->getSize(), null, true ); $form->add('file_hidden', 'hidden', array( 'mapped' => false, 'required' => false, 'empty_data' => $data['file_hidden'], )); $form->get('file')->setData($uploadedFile); $data['file'] = $uploadedFile; $event->setData($data); } } ); }
source share