I'm validating the file size when a user uploads a file, but I'm getting weird results when the file is too large:
Controller:
// Attachments form
$form = $this->createFormBuilder()
->add('file', 'file', array('label' => ' ',
))
->getForm();
if ($this->getRequest()->isMethod('post') && $form->bind($this->getRequest())->isValid()) {
$uploadedFile = $form['file']->getData();
...
}
Entity:
namespace Pro\Bundle\Entity;
use Symfony\Component\HttpFoundation\File\File as SymfonyFile;
/**
* @ORM\Entity
* @ORM\Table(name="file")
*/
class File
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
//more properties...
/**
* @var SymfonyFile
* @Constraints\File(maxSize=2000000) // <2 MB
*/
private $filesystemFile;
function __construct(SymfonyFile $file, $name)
{
$this->created = new \DateTime;
$this->setFilesystemFile($file);
$this->name = $name;
}
//more methods...
function setFilesystemFile(SymfonyFile $file)
{
$this->filesystemFile = $file;
}
}
So when a user submits a file, the isValid
method check the file size. If it is larger that 2000000B it will throw an error. But I'm getting weird results:
In localhost (upload_max_filesize = 2M
, post_max_size = 2M
):
If the file is too large I get two errors:
Token not valid.
The uploaded file is too large.
In VPS (upload_max_filesize = 2M
, post_max_size = 2M
):
If the file is too large, first try to upload the file, and then an Internal Server Error is thrown. Looking at the logs I can see the error is due to the invalid entity, because the file is too large. So it seems like it's trying to move the file, even if it's too large...
Did you try having a function like this in the Entity file and add a validation using validation.yml file?
public function isFilesystemFile()
{
$valid = false;
//do the validation such as file size is too large.
//then set the valid flag accordingly
return $valid;
}
In validation.yml file
Pro\Bundle\Entity\FilesystemFile:
getters:
FilesystemFile:
- "True": { message: "File size is too large." }
Hope this helps.
Cheers!