在Symfony的,我可以用接受MIME類型:文件上傳:如何使用斷言排除MIME類型?
/**
* @Assert\File(maxSize="10M", mimeTypes={"application/pdf", "image/png"})
*/
public $file;
但我怎麼能排除從該列表中的東西嗎?比方說,我想允許除PHP文件以外的所有上傳?
在Symfony的,我可以用接受MIME類型:文件上傳:如何使用斷言排除MIME類型?
/**
* @Assert\File(maxSize="10M", mimeTypes={"application/pdf", "image/png"})
*/
public $file;
但我怎麼能排除從該列表中的東西嗎?比方說,我想允許除PHP文件以外的所有上傳?
您可以通過斷言實現Callback constraint。此方法的一個優點是可以將錯誤消息應用於表單中的任何字段(或字段)。
use Symfony\Component\Validator\ExecutionContext;
/**
* @ORM\Entity()
* @Assert\Callback(methods={"validateFile"})
*/
class MyEntity
{
public function validateFile(ExecutionContext $context)
{
$path = $context->getPropertyPath();
if (/* $this->file is not in allowed mimeTypes ... */) {
$context->setPropertyPath($path . '.file');
$context->addViolation("Invalid file mimetype", array(), null);
}
}
}
您不需要創建任何回調來執行此操作。只要確保:
1)設置enable_annotations參數在您的應用程序如真/配置/ config.yml:
# app/config/config.yml
framework:
validation: { enable_annotations: true }
2)包括正確記錄實體文件驗證約束。
// YourEntity.php
use Symfony\Component\Validator\Constraints as Assert;
3)正確使用註解。例如:
// YourEntity.php
/**
* @Assert\File(
* maxSize="5242880",
* mimeTypes = {
* "image/png",
* "image/jpeg",
* "image/jpg",
* "image/gif",
* "application/pdf",
* "application/x-pdf"
* }
*)
*/
private $arquivo;
上面的代碼在我的Symfony 2.3.9上正常工作。
[]中
恐怕你需要創建自己的約束... – Florent
嗯,這就是我想通。非常感謝你清除那個。 – insertusernamehere
你應該**總是**白名單,而不是黑名單,只列出你允許的mimeTypes而不允許 – JamesHalsall