Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get file size in symfony2?

Tags:

symfony

I'm using following code to upload a file submitted through a form. How can I get file size before uploading it? I want the max file size to be 20mb.

$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));
    }
}
like image 271
Umair Malik Avatar asked Jun 04 '15 14:06

Umair Malik


1 Answers

Oldskool is correct. However if you want to retrieve the exact file size after it has been uploaded, you can use the following:

$fileSize = $file->getClientSize();

Another solution would be to change maximum size of upload file in php.ini. The following will echo the current file size limit.

echo $file->getMaxFilesize();

To get form errors, you should validate 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);
like image 176
eselskas Avatar answered Oct 11 '22 22:10

eselskas