Symfony2 -在上传之前验证文件大小


Symfony2 - Validate file size before uploading it

当用户上传文件时,我正在验证文件大小,但是当文件太大时,我得到奇怪的结果:

控制器:

// 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();
    ...
}
实体:

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;
    }
}

所以当用户提交文件时,isValid方法检查文件大小。如果它大于2000000B,它将抛出错误。但是我得到了奇怪的结果:

In localhost (upload_max_filesize = 2M, post_max_size = 2M):

如果文件太大,我得到两个错误:

令牌无效。

上传的文件太大。

In VPS (upload_max_filesize = 2M, post_max_size = 2M):

如果文件太大,首先尝试上传文件,然后抛出内部服务器错误。查看日志,我可以看到错误是由于无效实体造成的,因为文件太大。所以它看起来像是在移动文件,即使它太大了。

您是否尝试在实体文件中使用这样的函数并使用validation添加验证?yml文件?

public function isFilesystemFile()
{
  $valid = false;
  //do the validation such as file size is too large. 
  //then set the valid flag accordingly
  return $valid;
}

验证。yml文件

Pro'Bundle'Entity'FilesystemFile:
getters:
    FilesystemFile:
        - "True": { message: "File size is too large." }

希望对你有帮助。

干杯!