File

File

Validates that a value is a valid “file”, which can be one of the following:

  • A string (or object with a __toString() method) path to an existing file;
  • A valid Symfony\Component\HttpFoundation\File\File object (including objects of Symfony\Component\HttpFoundation\File\UploadedFile class).

This constraint is commonly used in forms with the FileType form field.

See also

If the file you’re validating is an image, try the Image constraint.

Applies toproperty or method
Options
ClassSymfony\Component\Validator\Constraints\File
ValidatorSymfony\Component\Validator\Constraints\FileValidator

Basic Usage

This constraint is most commonly used on a property that will be rendered in a form as a FileType field. For example, suppose you’re creating an author form where you can upload a “bio” PDF for the author. In your form, the bioFile property would be a file type. The Author class might look as follows:

  1. // src/Entity/Author.php
  2. namespace App\Entity;
  3. use Symfony\Component\HttpFoundation\File\File;
  4. class Author
  5. {
  6. protected $bioFile;
  7. public function setBioFile(File $file = null)
  8. {
  9. $this->bioFile = $file;
  10. }
  11. public function getBioFile()
  12. {
  13. return $this->bioFile;
  14. }
  15. }

To guarantee that the bioFile File object is valid and that it is below a certain file size and a valid PDF, add the following:

  • Annotations

    1. // src/Entity/Author.php
    2. namespace App\Entity;
    3. use Symfony\Component\Validator\Constraints as Assert;
    4. class Author
    5. {
    6. /**
    7. * @Assert\File(
    8. * maxSize = "1024k",
    9. * mimeTypes = {"application/pdf", "application/x-pdf"},
    10. * mimeTypesMessage = "Please upload a valid PDF"
    11. * )
    12. */
    13. protected $bioFile;
    14. }
  • YAML

    1. # config/validator/validation.yaml
    2. App\Entity\Author:
    3. properties:
    4. bioFile:
    5. - File:
    6. maxSize: 1024k
    7. mimeTypes: [application/pdf, application/x-pdf]
    8. mimeTypesMessage: Please upload a valid PDF
  • XML

    1. <!-- config/validator/validation.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping https://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
    6. <class name="App\Entity\Author">
    7. <property name="bioFile">
    8. <constraint name="File">
    9. <option name="maxSize">1024k</option>
    10. <option name="mimeTypes">
    11. <value>application/pdf</value>
    12. <value>application/x-pdf</value>
    13. </option>
    14. <option name="mimeTypesMessage">Please upload a valid PDF</option>
    15. </constraint>
    16. </property>
    17. </class>
    18. </constraint-mapping>
  • PHP

    1. // src/Entity/Author.php
    2. namespace App\Entity;
    3. use Symfony\Component\Validator\Constraints as Assert;
    4. use Symfony\Component\Validator\Mapping\ClassMetadata;
    5. class Author
    6. {
    7. public static function loadValidatorMetadata(ClassMetadata $metadata)
    8. {
    9. $metadata->addPropertyConstraint('bioFile', new Assert\File([
    10. 'maxSize' => '1024k',
    11. 'mimeTypes' => [
    12. 'application/pdf',
    13. 'application/x-pdf',
    14. ],
    15. 'mimeTypesMessage' => 'Please upload a valid PDF',
    16. ]));
    17. }
    18. }

The bioFile property is validated to guarantee that it is a real file. Its size and mime type are also validated because the appropriate options have been specified.

Note

As with most of the other constraints, null and empty strings are considered valid values. This is to allow them to be optional values. If the value is mandatory, a common solution is to combine this constraint with NotBlank.

Options

binaryFormat

type: boolean default: null

When true, the sizes will be displayed in messages with binary-prefixed units (KiB, MiB). When false, the sizes will be displayed with SI-prefixed units (kB, MB). When null, then the binaryFormat will be guessed from the value defined in the maxSize option.

For more information about the difference between binary and SI prefixes, see Wikipedia: Binary prefix.

disallowEmptyMessage

type: string default: An empty file is not allowed.

This constraint checks if the uploaded file is empty (i.e. 0 bytes). If it is, this message is displayed.

You can use the following parameters in this message:

ParameterDescription
{{ file }}Absolute file path
{{ name }}Base file name

groups

type: array | string

It defines the validation group or groups this constraint belongs to. Read more about validation groups.

maxSize

type: mixed

If set, the size of the underlying file must be below this file size in order to be valid. The size of the file can be given in one of the following formats:

SuffixUnit NameValueExample
(none)byte1 byte4096
kkilobyte1,000 bytes200k
Mmegabyte1,000,000 bytes2M
Kikibibyte1,024 bytes32Ki
Mimebibyte1,048,576 bytes8Mi

For more information about the difference between binary and SI prefixes, see Wikipedia: Binary prefix.

maxSizeMessage

type: string default: The file is too large ({{ size }} {{ suffix }}). Allowed maximum size is {{ limit }} {{ suffix }}.

The message displayed if the file is larger than the maxSize option.

You can use the following parameters in this message:

ParameterDescription
{{ file }}Absolute file path
{{ limit }}Maximum file size allowed
{{ name }}Base file name
{{ size }}File size of the given file
{{ suffix }}Suffix for the used file size unit (see above)

mimeTypes

type: array or string

If set, the validator will check that the mime type of the underlying file is equal to the given mime type (if a string) or exists in the collection of given mime types (if an array).

You can find a list of existing mime types on the IANA website.

Note

When using this constraint on a FileType field, the value of the mimeTypes option is also used in the accept attribute of the related <input type="file"/> HTML element.

This behavior is applied only when using form type guessing (i.e. the form type is not defined explicitly in the ->add() method of the form builder) and when the field doesn’t define its own accept value.

New in version 4.4: This feature was introduced in Symfony 4.4.

mimeTypesMessage

type: string default: The mime type of the file is invalid ({{ type }}). Allowed mime types are {{ types }}.

The message displayed if the mime type of the file is not a valid mime type per the mimeTypes option.

You can use the following parameters in this message:

ParameterDescription
{{ file }}Absolute file path
{{ name }}Base file name
{{ type }}The MIME type of the given file
{{ types }}The list of allowed MIME types

notFoundMessage

type: string default: The file could not be found.

The message displayed if no file can be found at the given path. This error is only likely if the underlying value is a string path, as a File object cannot be constructed with an invalid file path.

You can use the following parameters in this message:

ParameterDescription
{{ file }}Absolute file path

notReadableMessage

type: string default: The file is not readable.

The message displayed if the file exists, but the PHP is_readable() function fails when passed the path to the file.

You can use the following parameters in this message:

ParameterDescription
{{ file }}Absolute file path

payload

type: mixed default: null

This option can be used to attach arbitrary domain-specific data to a constraint. The configured payload is not used by the Validator component, but its processing is completely up to you.

For example, you may want to use several error levels to present failed constraints differently in the front-end depending on the severity of the error.

uploadCantWriteErrorMessage

type: string default: Cannot write temporary file to disk.

The message that is displayed if the uploaded file can’t be stored in the temporary folder.

This message has no parameters.

uploadErrorMessage

type: string default: The file could not be uploaded.

The message that is displayed if the uploaded file could not be uploaded for some unknown reason.

This message has no parameters.

uploadExtensionErrorMessage

type: string default: A PHP extension caused the upload to fail.

The message that is displayed if a PHP extension caused the file upload to fail.

This message has no parameters.

uploadFormSizeErrorMessage

type: string default: The file is too large.

The message that is displayed if the uploaded file is larger than allowed by the HTML file input field.

This message has no parameters.

uploadIniSizeErrorMessage

type: string default: The file is too large. Allowed maximum size is {{ limit }} {{ suffix }}.

The message that is displayed if the uploaded file is larger than the upload_max_filesize php.ini setting.

You can use the following parameters in this message:

ParameterDescription
{{ limit }}Maximum file size allowed
{{ suffix }}Suffix for the used file size unit (see above)

uploadNoFileErrorMessage

type: string default: No file was uploaded.

The message that is displayed if no file was uploaded.

This message has no parameters.

uploadNoTmpDirErrorMessage

type: string default: No temporary folder was configured in php.ini.

The message that is displayed if the php.ini setting upload_tmp_dir is missing.

This message has no parameters.

uploadPartialErrorMessage

type: string default: The file was only partially uploaded.

The message that is displayed if the uploaded file is only partially uploaded.

This message has no parameters.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.