How to get file size in symfony2?

I am using the following code to upload a file submitted via a form. How can I get the file size before downloading it? I want the maximum file size to be 20 MB.

$file = $data->getFileName();
if ($file instanceof UploadedFile) {
    $uploadManager = $this->get('probus_upload.upload_manager.user_files');
    if ($newFileName = $uploadManager->move($file)) {
        $data->setFileName(basename($newFileName));
    }
}
+4
source share
2 answers

Old school is faithful. However, if you want to get the exact file size after downloading it, you can use the following:

$fileSize = $file->getClientSize();

Another solution would be to change the maximum upload file size in php.ini. The current file size limit will be displayed below.

echo $file->getMaxFilesize();

To get errors in the form, you must check the form and print any errors if the validation fails.

//include at the top of controller
use Symfony\Component\HttpFoundation\Response;

$form = $this->createForm(new FileType(), $file);

$form->handleRequest($request);

if ($form->isValid()) {
    //store data
    $data = "stored successfully";
    $statusCode = 200;
} else {
    //return errors if form is invalid
    $data = $form->getErrors();
    $statusCode = 500;
}

return new Response($data, $statusCode);
+4
source

Just add the File object to your Entity using the parameter maxSize:

/**
 * @Assert\File(
 *     maxSize = "20M"
 * )
 */
protected $userFiles;

Also see the documentation for more information.

+2
source

All Articles