Symfony2 将上传的文件分配到内存 [英] Symfony2 allocates uploaded file to memory

查看:28
本文介绍了Symfony2 将上传的文件分配到内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当在 Symfony 中上传大于 post_max_size 的文件时,上传的文件被分配在内存中.

While uploading a file bigger than post_max_size in Symfony, the uploaded file is allocated in the memory.

致命错误: 150994944 字节的允许内存大小已用完(已尝试分配 84627994 字节)在/Applications/MAMP/htdocs/Symfony/vendor/symfony/src/Symfony/Component/HttpKernel/DataCollector/DataCollector.php在线 28

Fatal error: Allowed memory size of 150994944 bytes exhausted (tried to allocate 84627994 bytes) in /Applications/MAMP/htdocs/Symfony/vendor/symfony/src/Symfony/Component/HttpKernel/DataCollector/DataCollector.php on line 28

为什么 symfony 试图在 POST 时将文件分配到内存?

1/php.ini

file_uploads = On
upload_tmp_dir = /Applications/MAMP/tmp/php
upload_max_filesize = 32M
post_max_size = 48M

2/控制器

<?php
//AcmeDemoBundle/Controller/DemoController
namespace Acme\DemoBundle\Controller;
use Symfony\Component\HttpFoundation\Request;

class DemoController extends Controller
{

public function createAction(Request $request)
{

    if ($request->getMethod() == 'POST')
    {
        if ($_FILES["file"]["size"] < 3000000 )//3Mb
        {
            if ($_FILES["file"]["error"] > 0)
            {
                echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
            }
            else
            {
                if (empty($_POST) && empty($_FILES) && isset($_SERVER['REQUEST_METHOD']) && strtolower($_SERVER['REQUEST_METHOD']) == 'post')
                {
                    echo "The file is bigger than post_max_size in php.ini.";
                }
                else
                {
                    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";

                    if (file_exists("upload/" . $_FILES["file"]["name"]))
                    {
                        echo $_FILES["file"]["name"] . " already exists. ";
                    }
                    else
                    {
                        move_uploaded_file($_FILES["file"]["tmp_name"],
                            "upload/" . $_FILES["file"]["name"]);
                        echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
                    }
                }
            }
        }
        else
        {
            echo "Invalid file";
        }

    }

    return $this->container->get('templating')->renderResponse('AcmeDemoBundle:Demo:create.html.twig');

}

3/模板

//AcmeDemoBundle/Resources/views/Demo/create.html.twig
{% extends "AcmeDemoBundle::layout.html.twig" %}

{% block content %}

<h1>Upload File</h1>

<form action="#" method="post"
      enctype="multipart/form-data">
    <label name="file">Filename:</label>
    <input type="file" name="file" id="file" />
    <br />
    <input type="submit" name="submit" value="Submit" />
</form>

{% endblock %}

推荐答案

我假设您正在通过 app_dev.php 前端控制器尝试使用 symfony.

I assume that you're trying symfony via the app_dev.php front controller.

默认情况下,在开发环境中,分析器为每个请求启用.

By default, in the dev environment, the profiler is enabled for every requests.

framework:
    profiler: { only_exceptions: false }

只需将 only_exceptions 参数从 false 更改为 true,然后重试.

Just change the only_exceptions param from false to true, and try again.

框架:探查器:{ only_exceptions: true }

framework: profiler: { only_exceptions: true }

您应该使用框架为您提供的工具来处理文件上传.

You should use the tools that the framework provides you to handle file upload.

行动:

public function createAction(Request $request)
{
    $form = $this->createFormBuilder()
        ->add('attachment', 'file')
        ->getForm();

    if ($request->getMethod() == 'POST') {
        $form->bindRequest($request);

        if ($form->isValid()) {
            $file = $form['attachment']->getData(); /** @var $file \Symfony\Component\HttpFoundation\File\UploadedFile */

            echo $file->getClientSize();
        }
    }

    return $this->render('AcmeDemoBundle:Demo:create.html.twig', array(
        'form' => $form->createView(),
    ));
}

模板:

{% extends "AcmeDemoBundle::layout.html.twig" %}

{% block content %}

<h1>Upload File</h1>

<form action="" method="post" {{ form_enctype(form) }}>
    {{ form_errors(form) }}

    {{ form_row(form.attachment) }}

    {{ form_rest(form) }}

    <input type="submit" />
</form>

{% endblock %}

使用此代码,php 永远不会超过内存使用量.如果文件过大,表单会报错,if($form->isValid())"里面的代码不会被执行.

With this code, php never exceeds memory usage. If the file is too big, the form show an error, and the code inside "if ($form->isValid())" is not executed.

查看表单文档:http://symfony.com/doc/current/book/forms.html以及文件"字段类型的参考:http://symfony.com/doc/current/reference/forms/types/file.html

Have a look at the form documentation : http://symfony.com/doc/current/book/forms.html and the reference for the "file" field type : http://symfony.com/doc/current/reference/forms/types/file.html

这篇关于Symfony2 将上传的文件分配到内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆