Symfony 表单 mime 类型应该只接受 PDF 文件

标签 symfony doctrine-orm symfony-forms

我试图让我的 Symfony2 程序只接受 PDF 文件。 在我的实体类中:

/**
 * File
 *
 * @var File
 *
 * @Assert\File(
 *      maxSize = "5M",
 *      mimeTypes = {"application/pdf", "application/x-pdf"},
 *      maxSizeMessage = "The maxmimum allowed file size is 5M.",
 *      mimeTypesMessage = "Please upload a valid PDF"
 * )
 */
protected $file;

问题是为什么我仍然可以上传其他文件。我目前正在通过 REST API 上传。

代码:

    public function postFileAction(Request $request){

    $name = $request->get('name');
    $path = $request->get('path');
    $file = $request->files->get('file');

    $filesTest = new FilesTest();
    $filesTest->setName($name);
    $filesTest->setFile($file);;

    $manager = $this->getDoctrine()->getManager();
    $manager->persist($filesTest);
    $manager->flush();
    }

我是 symfony2 的新手,所以我可能误解了如何处理这个问题。有没有人有什么建议?

最佳答案

您实际上并没有验证这些验证规则。

试试这个:

public function postFileAction(Request $request)
{
    $name = $request->get('name');
    $path = $request->get('path');
    $file = $request->files->get('file');

    $filesTest = new FilesTest();
    $filesTest->setName($name);
    $filesTest->setFile($file);

    $validator = $this->get('validator'); // Assuming ContainerAware
    $errors    = $validator->validate($filesTest);

    if (count($errors) > 0) {
        // Handle your errors here
    } else {
        $manager = $this->getDoctrine()->getManager();
        $manager->persist($filesTest);
        $manager->flush();
    }

    // Return your response etc...
}

如果您想了解有关这种验证方式的更多信息,请查看此处:http://symfony.com/doc/current/book/validation.html

在使用 REST 的同时,您还可以欺骗表单提交,因此,不要排除也使用表单。

关于Symfony 表单 mime 类型应该只接受 PDF 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24084384/

相关文章:

symfony 2.2 getChild 已弃用

php - 如何使用 Doctrine 的 ArrayCollection::exists 方法

mongodb - Symfony 2 StofDoctrineExtensionBundle 时间戳与 odm (MongoDB)

php - Symfony2 : How to change hidden field value on PRE_SUBMIT

php - 异常 : "Could not gather sufficient random data"

symfony - 添加新用户时 FOS 用户错误

php - doctrine2 和 group_concat

forms - Symfony2 : problems rendering the translation-form with A2lixTranslationFormBundle and Gedmo\DoctrineExtensions Translatable

php - Symfony/propel 表单保存具有附加属性的对象

php - Symfony - npm 更新未修复漏洞