使用 Symfony 进行简单文件上传验证请求

bls*_*lsn 3 php validation symfony

验证 HTML 表单的输入字段是一个简单的操作,如下所示:

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Validation;
use Symfony\Component\Validator\Constraints as Assert;

    public function adminPassword(Request $request) 
    {
        $this->parameters = $request->request->all();
           ...
        $new_password = $this->parameters['new_password'];
        $validator = Validation::createValidator();
        $violations = $validator->validate($new_password, [
            new Assert\Length([
                'min' => 4
            ])
        ]);
        if (0 !== count($violations)) {
            ...
        }
           ...
    }
Run Code Online (Sandbox Code Playgroud)

Symfony 可以以同样简单的方式完成 HTML 表单文件上传(图像)的验证请求吗?

public function logoUpload(Request $request)
{
     $file = $request->files->get('logo');
     ...
}
Run Code Online (Sandbox Code Playgroud)

要求不使用 Twig 或 Symfony 'Form' ('createFormBuilder'),如上所述。

Tho*_*the 5

在 Symfony 中, 的结果$request->files->get('key')UploadedFileor null

UploadedFile您可以使用带有文件约束的验证器,如下例所示:

use Symfony\Component\Validator\Constraints\File; 
use Symfony\Component\Validator\ConstraintViolationListInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Validation;

...

public function validateFile(Request $request): ConstraintViolationListInterface
{
   $fileConstraints = new File([
       'maxSize' => '64M',
       'maxSizeMessage' => 'The file is too big',
       'mimeTypes' => ['pdf' => 'application/pdf'],
       'mimeTypesMessage' => 'The format is incorrect, only PDF allowed'
   ]);

   $validator = Validation::createValidator();
   
   return $validator->validate($request->files->get('key'), $fileConstraints);
}
Run Code Online (Sandbox Code Playgroud)

该方法返回约束的迭代器。

请注意,要使用 MimeTypes,您需要在应用程序上安装 symfony/mime

  • 运行“composer require symfony/mime”后,我得到了验证工作,谢谢。 (2认同)