phpsymfonycsvdoctrine-orm

Symfony2 Restrict end user to upload only csv file


In my symfony2 application, I am using doctrine and I want user to upload only csv file.

Below is my code I have set for validation in my entity file:

use Symfony\Component\Validator\Constraints as Assert;

/**
 * @var string
 * @Assert\File( maxSize = "1024k", mimeTypes = {"text/csv"}, mimeTypesMessage = "Please   upload a valid CSV File")
 * @ORM\Column(name="filename", type="string", length=255)
 */
private $filename;

But still its not allowing me to upload the csv file too.


Solution

  • Following your comment : "The mime type of the file is invalid ("text/plain"). Allowed mime types are "text/csv".

    After some search, Symfony 2 is using the finfo() function. You can read Php doesn't return the correct mime type :

    Pekka 웃: "I'm not intimately familiar with the workings of fileinfo, but I think this is normal. Text files (and that's what CSS and JS are) provide no clear pointers as to what content it has. They have no header bytes, no defined structure. So all poor fileinfo can do is guess - with poor results, as you can see.

    I think to successfully verify the contents of .js and .css files, you have to either rely on the extension, or actually parse them with the correct, appropriate parser."

    So this is not a bug and the only way is to implement your own logic (in your FormBuilder) or like tutty said you can create your custom constraint.

    Edit:

    Following your comment, here's where Symfony 2 finfo() is used: Component/HttpFoundation/File/MimeType/FileinfoMimeTypeGuesser.php