如何在symfony2中获取文件大小?

Uma*_*lik 5 symfony

我正在使用以下代码上传通过表单提交的文件。上传之前如何获取文件大小?我希望最大文件大小为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));
    }
}
Run Code Online (Sandbox Code Playgroud)

ese*_*kas 5

Oldskool是正确的。但是,如果要在上传后检索确切的文件大小,可以使用以下命令:

$fileSize = $file->getClientSize();
Run Code Online (Sandbox Code Playgroud)

另一个解决方案是在php.ini中更改上传文件的最大大小。以下将回显当前文件的大小限制。

echo $file->getMaxFilesize();
Run Code Online (Sandbox Code Playgroud)

要获取表单错误,您应该验证表单并在验证失败时打印任何错误。

//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);
Run Code Online (Sandbox Code Playgroud)


Old*_*ool 3

只需使用以下选项注释实体中的 File 对象maxSize

/**
 * @Assert\File(
 *     maxSize = "20M"
 * )
 */
protected $userFiles;
Run Code Online (Sandbox Code Playgroud)

另请参阅有关此内容的文档以获取更多详细信息。