Symfony
sponsored by SensioLabs
Menu
  • About
  • Documentation
  • Screencasts
  • Cloud
  • Certification
  • Community
  • Businesses
  • News
  • Download
  1. Home
  2. Documentation
  3. Reference
  4. Constraints
  5. File
  • Documentation
  • Book
  • Reference
  • Bundles
  • Cloud
Search by Algolia

Table of Contents

  • Basic Usage
  • Options
    • maxSize
    • mimeTypes
    • maxSizeMessage
    • mimeTypesMessage
    • notFoundMessage
    • notReadableMessage
    • uploadIniSizeErrorMessage
    • uploadFormSizeErrorMessage
    • uploadErrorMessage

File

Edit this page

Warning: You are browsing the documentation for Symfony 2.0, which is no longer maintained.

Read the updated version of this page for Symfony 6.2 (the current stable version).

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 File object (including objects of class UploadedFile).

This constraint is commonly used in forms with the file form type.

Tip

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

Applies to property or method
Options
  • maxSize
  • mimeTypes
  • maxSizeMessage
  • mimeTypesMessage
  • notFoundMessage
  • notReadableMessage
  • uploadIniSizeErrorMessage
  • uploadFormSizeErrorMessage
  • uploadErrorMessage
Class File
Validator FileValidator

Basic Usage

This constraint is most commonly used on a property that will be rendered in a form as a file form type. 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// src/Acme/BlogBundle/Entity/Author.php
namespace Acme\BlogBundle\Entity;

use Symfony\Component\HttpFoundation\File\File;

class Author
{
    protected $bioFile;

    public function setBioFile(File $file = null)
    {
        $this->bioFile = $file;
    }

    public function getBioFile()
    {
        return $this->bioFile;
    }
}

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:

  • YAML
  • Annotations
  • XML
  • PHP
1
2
3
4
5
6
7
8
# src/Acme/BlogBundle/Resources/config/validation.yml
Acme\BlogBundle\Entity\Author:
    properties:
        bioFile:
            - File:
                maxSize: 1024k
                mimeTypes: [application/pdf, application/x-pdf]
                mimeTypesMessage: Please upload a valid PDF
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// src/Acme/BlogBundle/Entity/Author.php
namespace Acme\BlogBundle\Entity;

use Symfony\Component\Validator\Constraints as Assert;

class Author
{
    /**
     * @Assert\File(
     *     maxSize = "1024k",
     *     mimeTypes = {"application/pdf", "application/x-pdf"},
     *     mimeTypesMessage = "Please upload a valid PDF"
     * )
     */
    protected $bioFile;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
<!-- src/Acme/BlogBundle/Resources/config/validation.xml -->
<class name="Acme\BlogBundle\Entity\Author">
    <property name="bioFile">
        <constraint name="File">
            <option name="maxSize">1024k</option>
            <option name="mimeTypes">
                <value>application/pdf</value>
                <value>application/x-pdf</value>
            </option>
            <option name="mimeTypesMessage">Please upload a valid PDF</option>
        </constraint>
    </property>
</class>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// src/Acme/BlogBundle/Entity/Author.php
namespace Acme\BlogBundle\Entity;

use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Constraints as Assert;

class Author
{
    public static function loadValidatorMetadata(ClassMetadata $metadata)
    {
        $metadata->addPropertyConstraint('bioFile', new Assert\File(array(
            'maxSize' => '1024k',
            'mimeTypes' => array(
                'application/pdf',
                'application/x-pdf',
            ),
            'mimeTypesMessage' => 'Please upload a valid PDF',
        )));
    }
}

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.

Options

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:

  • bytes: To specify the maxSize in bytes, pass a value that is entirely numeric (e.g. 4096);
  • kilobytes: To specify the maxSize in kilobytes, pass a number and suffix it with a lowercase "k" (e.g. 200k);
  • megabytes: To specify the maxSize in megabytes, pass a number and suffix it with a capital "M" (e.g. 4M).

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

maxSizeMessage

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

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

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.

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.

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.

uploadIniSizeErrorMessage

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

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

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.

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, such as the file upload failed or it couldn't be written to disk.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
We stand with Ukraine.
Version:
Measure & Improve Symfony Code Performance

Measure & Improve Symfony Code Performance

Check Code Performance in Dev, Test, Staging & Production

Check Code Performance in Dev, Test, Staging & Production

↓ Our footer now uses the colors of the Ukrainian flag because Symfony stands with the people of Ukraine.

Avatar of Marcel Korpel, a Symfony contributor

Thanks Marcel Korpel for being a Symfony contributor

2 commits • 28 lines changed

View all contributors that help us make Symfony

Become a Symfony contributor

Be an active part of the community and contribute ideas, code and bug fixes. Both experts and newcomers are welcome.

Learn how to contribute

Symfony™ is a trademark of Symfony SAS. All rights reserved.

  • What is Symfony?
    • Symfony at a Glance
    • Symfony Components
    • Case Studies
    • Symfony Releases
    • Security Policy
    • Logo & Screenshots
    • Trademark & Licenses
    • symfony1 Legacy
  • Learn Symfony
    • Symfony Docs
    • Symfony Book
    • Reference
    • Bundles
    • Best Practices
    • Training
    • eLearning Platform
    • Certification
  • Screencasts
    • Learn Symfony
    • Learn PHP
    • Learn JavaScript
    • Learn Drupal
    • Learn RESTful APIs
  • Community
    • SymfonyConnect
    • Support
    • How to be Involved
    • Code of Conduct
    • Events & Meetups
    • Projects using Symfony
    • Downloads Stats
    • Contributors
    • Backers
  • Blog
    • Events & Meetups
    • A week of symfony
    • Case studies
    • Cloud
    • Community
    • Conferences
    • Diversity
    • Documentation
    • Living on the edge
    • Releases
    • Security Advisories
    • SymfonyInsight
    • Twig
    • SensioLabs
  • Services
    • SensioLabs services
    • Train developers
    • Manage your project quality
    • Improve your project performance
    • Host Symfony projects
    Deployed on
Follow Symfony
Search by Algolia