Ali Briceño
Ali Briceño

Reputation: 1134

How to know uploaded file size on symfony 3?

i use FOSRestbundle to manage my api. I implemented a action to upload a file on symfony that it's working well. But the problem is that i need to obtain the file size... My action get the file on this way:

$uploadedfile = $request->files->get('file');

this obtains an array of all files that i upload.

Reading the doc of symfony for the $uploadedfile object, there is a method called:

getClientSize()

so i used and always return 0:

$fileSize = $uploadedfile->getClientSize();

There are another way to get the file size? I'm doing something wrong?

Thanks a lot.

Upvotes: 0

Views: 5172

Answers (2)

Confidence
Confidence

Reputation: 2303

how about the solution here?

http://symfony.com/doc/current/reference/constraints/File.html#maxsize

// src/AppBundle/Entity/Author.php
namespace AppBundle\Entity;

use Symfony\Component\Validator\Constraints as Assert;

class Author
{
    /**
     * @Assert\File(
     *     maxSize = "1024k",
     *     mimeTypes = {"application/pdf", "application/x-pdf"},
     *     mimeTypesMessage = "Please upload a valid PDF"
     * )
     */
    protected $bioFile;
}

you might have to create an entity for that, if you have not done so.

So if you want to use validation in your controller, you would do something like

// ...
use Symfony\Component\HttpFoundation\Response;
use AppBundle\Entity\Author;

// ...
public function authorAction()
{
    $author = new Author();

    // ... do something to the $author object

    $validator = $this->get('validator');
    $errors = $validator->validate($author);

    if (count($errors) > 0) {

        $errorsString = (string) $errors;

        return new Response($errorsString);
    }

    return new Response('The author is valid! Yes!');
}

you can test it, by uploading a file larger than the maxsize, set in your given Author Entity in that case you would get the message "Please upload a valid PDF"

Upvotes: 0

r4ccoon
r4ccoon

Reputation: 3136

Have you successfully moved the file into the intended folder? if you have, you can just call a native php function filesize().

http://php.net/manual/en/function.filesize.php

Upvotes: 0

Related Questions