我在下面提出了解决方案。您可以根据自己的需要对其进行调整。但是您需要额外的命令来清理 uploads/tmp 目录中的旧文件。您需要在配置中的参数部分下有两个参数:
parameters:
uploads_dir: %kernel.root_dir%/../web/uploads
uploads_tmp_dir: %uploads_dir%/tmp
表格:
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);
}
}
);
}