New in Symfony 2.6: Support for KiB and MiB units in FileValidator

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

Comments

Thanks for the review but I think the PR is not the right one. I don't really see the link between kibibytes (what a great name :D) and "[Translation] [Xliff] Support for ". Am I wrong ?
@Titouan, thanks for reporting this error. The real PR related to this feature is #11027. I've just fixed the original blog post.

(The previous PR is made by the same developer and is related to another feature that we'll explain in a future blog post in this "New in Symfony 2.6" series).
@Javier, is there any chance to get those nice contribution boxes inside the "New in Symfony" articles back?
@Christian we'll get them back, but right now is a low priority thing in a huge pile of things to do. But don't worry because I'll return to these posts and I'll update them.

And of course, thanks for your comment and for pushing us to improve :)
@Javier Thanks for your feedback and the great work you do.
There is a typo on the last line (1204 bytes). Thanks for this nice PR presentation.
@Soyel thanks for reporting this error. I've just fixed it.
"However, in some computer science contexts, kilo is usually interpreted as 1,024"

I would say that in most cases 1Kb = 1024b.
1Kb = 1000 only for referring to data transfer rates and to disk storage space (for marketing reasons)

Comments are closed.

To ensure that comments stay relevant, they are closed for old posts.