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



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

use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentValidatorValidation;
use SymfonyComponentValidatorConstraints 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 AssertLength([
'min' => 4
])
]);
if (0 !== count($violations)) {
...
}
...
}

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

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

该要求未使用Twig或Symfony"Form"("createFormBuilder"(,如上文所述。

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

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

use SymfonyComponentValidatorConstraintsFile; 
use SymfonyComponentValidatorConstraintViolationListInterface;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentValidatorValidation;
...
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);
}

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

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

最新更新