文件上传 Symfony
File Upload Symfony
我想在我的表单中上传多张图片。
事实上,是可行的,但只适用于小尺寸的图片(比如小于 1Mo)。当我尝试用 4/5Mo 上传图片时,出现此错误:文件“”不存在
我注意到这是由于尺寸的原因,因为对于小图像它效果很好。
所以,我的代码:
与Activity相关的实体图片:
/**
* @ORM\Column(type="string")
* @Assert\NotBlank(message="Please, upload the product brochure as a PNG, GIF, JPEG or JPG file.")
* @Assert\File(mimeTypes = {"image/png","image/jpeg","image/jpg","image/gif"})
* @Assert\File(maxSize="50M")
*/
private $url;
/**
* @ORM\Column(type="text", nullable=true)
*/
private $legende;
/**
* @ORM\Column(type="datetime")
*/
private $createdAt;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Activity", inversedBy="pictures")
*/
private $activity;
表格图片类型:
->add('url', FileType::class, array('label' => 'Image (JPG, JPEG, PNG, GIF)'))
和控制器,在创建activity(图片形式在这里,当你添加一个activity时,你可以选择添加一张或多张图片)
/**
* @Route("/create_activity", name="create_activity")
*/
public function create_activity(Request $request, ObjectManager $manager){
$activity = new Activity();
$form = $this->createForm(ActivityType::class, $activity);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$pictures = $activity->getPictures(); // On récupère toutes les photos ajoutées
if($pictures){ // S'il y a des photos
foreach ($pictures as $picture ) { // Pour chaque photo
$file = $picture->getUrl(); // On récupère l'url uploadé
// ERROR COMING HERE at $file->guessExtension();
$fileName = $this->generateUniqueFileName().'.'.$file->guessExtension(); // On génère un nom de fichier
// Move the file to the directory where brochures are stored
try {
$file->move( // On l'ajoute dans le répertoire
$this->getParameter('pictures_directory'),
$fileName
);
} catch (FileException $e) {
// ... handle exception if something happens during file upload
}
$picture->setUrl($fileName);
}
}
$activity->setCreatedAt(new \DateTime());
$activity->setDeleted(0);
$manager->persist($activity);
$manager->flush();
return $this->redirectToRoute('show_activity', ['id' => $activity->getId()]);
}
return $this->render('activity/create_activity.html.twig', [
'formActivity' => $form->createView(),
'activity' => $activity
]);
}
我做了很多'echo; exit;' 知道错误来自哪里,她来自“$file->guessExtension();”
非常感谢您的帮助!
如果您的 $file
是 UploadedFile
的一个实例(在您的情况下应该如此),您可以使用方法 $file->getError()
来了解在上传您的文件。
此方法将 return 一个 integer
对应于此文档:http://php.net/manual/en/features.file-upload.errors.php
在你的情况下,我敢打赌你会遇到 UPLOAD_ERR_INI_SIZE
错误。
要解决这个问题,您可以在此处查看解决方案:Change the maximum upload file size
编辑
下面是一个例子:
/** @var UploadedFile $file */
$file = $picture->getUrl();
if (UPLOAD_ERR_OK !== $file->getError()) {
throw new UploadException($file->getErrorMessage());
}
我想在我的表单中上传多张图片。 事实上,是可行的,但只适用于小尺寸的图片(比如小于 1Mo)。当我尝试用 4/5Mo 上传图片时,出现此错误:文件“”不存在
我注意到这是由于尺寸的原因,因为对于小图像它效果很好。
所以,我的代码: 与Activity相关的实体图片:
/**
* @ORM\Column(type="string")
* @Assert\NotBlank(message="Please, upload the product brochure as a PNG, GIF, JPEG or JPG file.")
* @Assert\File(mimeTypes = {"image/png","image/jpeg","image/jpg","image/gif"})
* @Assert\File(maxSize="50M")
*/
private $url;
/**
* @ORM\Column(type="text", nullable=true)
*/
private $legende;
/**
* @ORM\Column(type="datetime")
*/
private $createdAt;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Activity", inversedBy="pictures")
*/
private $activity;
表格图片类型:
->add('url', FileType::class, array('label' => 'Image (JPG, JPEG, PNG, GIF)'))
和控制器,在创建activity(图片形式在这里,当你添加一个activity时,你可以选择添加一张或多张图片)
/**
* @Route("/create_activity", name="create_activity")
*/
public function create_activity(Request $request, ObjectManager $manager){
$activity = new Activity();
$form = $this->createForm(ActivityType::class, $activity);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$pictures = $activity->getPictures(); // On récupère toutes les photos ajoutées
if($pictures){ // S'il y a des photos
foreach ($pictures as $picture ) { // Pour chaque photo
$file = $picture->getUrl(); // On récupère l'url uploadé
// ERROR COMING HERE at $file->guessExtension();
$fileName = $this->generateUniqueFileName().'.'.$file->guessExtension(); // On génère un nom de fichier
// Move the file to the directory where brochures are stored
try {
$file->move( // On l'ajoute dans le répertoire
$this->getParameter('pictures_directory'),
$fileName
);
} catch (FileException $e) {
// ... handle exception if something happens during file upload
}
$picture->setUrl($fileName);
}
}
$activity->setCreatedAt(new \DateTime());
$activity->setDeleted(0);
$manager->persist($activity);
$manager->flush();
return $this->redirectToRoute('show_activity', ['id' => $activity->getId()]);
}
return $this->render('activity/create_activity.html.twig', [
'formActivity' => $form->createView(),
'activity' => $activity
]);
}
我做了很多'echo; exit;' 知道错误来自哪里,她来自“$file->guessExtension();”
非常感谢您的帮助!
如果您的 $file
是 UploadedFile
的一个实例(在您的情况下应该如此),您可以使用方法 $file->getError()
来了解在上传您的文件。
此方法将 return 一个 integer
对应于此文档:http://php.net/manual/en/features.file-upload.errors.php
在你的情况下,我敢打赌你会遇到 UPLOAD_ERR_INI_SIZE
错误。
要解决这个问题,您可以在此处查看解决方案:Change the maximum upload file size
编辑
下面是一个例子:
/** @var UploadedFile $file */
$file = $picture->getUrl();
if (UPLOAD_ERR_OK !== $file->getError()) {
throw new UploadException($file->getErrorMessage());
}