Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple file upload validate request with Symfony

Validate an input field of HTML form is a simple operation, as follows:

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)) {
            ...
        }
           ...
    }

Can validation request of HTML form file upload (image), can be done by Symfony in the same simple way?

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

The requirement is not using Twig, or Symfony 'Form' ('createFormBuilder'), as not done above.

like image 848
blsn Avatar asked Oct 24 '25 02:10

blsn


1 Answers

In Symfony, the result of $request->files->get('key') is an UploadedFile or null.

With an UploadedFile you can use your validator with a file constraint as the example below :

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);
}

The method returns an iterator of constraints.

Please note to use MimeTypes you need to install symfony/mime on your app

like image 88
Thomas Lamothe Avatar answered Oct 26 '25 17:10

Thomas Lamothe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!