Jérémy Derussé
Contributed by Jérémy Derussé in #11027

How many bytes are in 3 kilobytes? Strictly speaking, the kilo prefix always refers to 1,000, so the answer may be 3,000 bytes. However, in some computer science contexts, kilo is usually (and wrongly) interpreted as 1,024 so the answer could also be 3,072 bytes.

In order to solve these issues, the IEC (International Electrotechnical Commission) established in 1998 the binary units (Ki, Mi, Gi, etc.) to distinguish them from the traditional units (K, M, G, etc.) For instance, the kibibyte unit refers to 1,024 bytes, instead of the 1,000 bytes associated with the kilobyte.

As of Symfony 2.6, you can use the Ki and Mi units to set the maximum file size of the FileValidator constraint:

1
2
3
4
5
6
7
8
9
10
11
12
use Symfony\Component\Validator\Constraints as Assert;

class Author
{
    /**
     * @Assert\File(
     *     maxSize = "100Ki",
     *     maxSizeMessage = "Allowed maximum size is {{ limit }} {{ suffix }}"
     * )
     */
    protected $bioFile;
}

The annotations of the previous example set the maximum file size to 100 kibibytes, which equals to 102,400 bytes. Changing the constraint value to 100K would limit the file size up to 100,000 bytes.

In addition to the new Ki unit, you can also use the Mi to set the maximum file size in mebibytes, which equal to 1,048,576 bytes (1,024 * 1,024 bytes).

Published in #Living on the edge