【发布时间】:2019-08-06 17:19:33
【问题描述】:
你好,我是 symfony 的新手,我必须和他一起制作产品的 CRUD。 我必须将此信息发送到数据库:
- 标题(字符串,必填,最小长度:6);
- 说明(文本,最大长度:4000)
- 图像(blob,必需,最大文件大小:5mb,仅类型:JPG、PNG、GIF);
- 库存(int,必填);
问题:
- 大小超过 1mb 的文件不会通过表单发送;
观察:
- 如果文件大小为 1mb 或更少,则表单会正确发送。
我的实体:
/**
* @ORM\Entity(repositoryClass="App\Repository\ProductRepository")
*/
class Product {
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
*/
private $title;
/**
* @ORM\Column(type="text", length=4000, nullable=true)
*/
private $description;
/**
* @ORM\Column(type="blob")
*/
private $image;
/**
* @ORM\Column(type="integer")
*/
private $stock;
我的表单由以下人员生成:
$product = new Product();
$form = $this->createFormBuilder($product)
->add('title',TextType::class, [
'required' => true,
'label' => 'Titulo: ',
'attr' => ['minlength' => 6, 'id' => 'title_product'],
])
->add('description', TextareaType::class,[
'required' => false,
'label' => 'Descrição: ',
'attr' => ['maxlength' => 4000, 'id' => 'description_product'],
])
->add('image', FileType::class, [
'required' => true,
'attr' => ['accept' => 'image/jpeg, image/png, image/gif'],
'label' => 'Imagem do produto(JPG, PNG ou GIF): ',
'help' => 'A imagem deve ter um peso maximo de 5 MBs.',
])
->add('stock', IntegerType::class, [
'required' => true,
'label' => 'Quantidade em estoque: ',
])
->add('save', SubmitType::class, [
'label' => 'Criar Produto',
'attr' => ['class' => 'btn btn-success']
])
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$product = $form->getData();
if ($this->validateFormProduct($product)){
$this->createProduct($product);
return $this->redirectToRoute('index_products');
}
}
return $this->render('product/new.html.twig', [
'form' => $form->createView()
]);
验证功能:
private function invalidImageType($img) {
$permitedTypes = array(IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF);
$detectedType= exif_imagetype($img);
return !in_array($detectedType, $permitedTypes);
}
private function invalidImageSize($img) {
return filesize($img) > 5000000;
}
private function validateFormProduct($form){
if ($this->invalidImageType($form->getImage())){
$this->addFlash(
'warning',
'Tipo de imagem invalido!'
);
return false;
}
if ($this->invalidImageSize($form->getImage())){
$this->addFlash(
'warning',
'Este arquivo excede o tamanho maximo de 5mb!'
);
return false;
}
return true;
}
函数加密:
private function encriptImage($img) {
$normalizer = new DataUriNormalizer();
return $normalizer->normalize(new \SplFileObject($img));
}
【问题讨论】:
-
这是 Symfony,不是 Synfony :)
标签: php forms image file symfony