Symfony2在Ajax调用时收到HTTP 500错误

时间:2014-02-11 16:53:53

标签: ajax symfony upload uploadify

我试图使用Uploadify来处理我在Symfony2中上传的文件。图像上传应该调用控制器,控制器内部将获取当前登录用户,根据当前用户名创建子目录,然后将文件移动到该文件夹​​。问题是当我运行$ user-&gt; getUsername()或与$ user对象相关的任何其他函数时,上传失败并出现HTTP 500错误,但是当我从URL运行此控制器时,一切正常。< / p>

以下是一些代码:

uploadify的前端配置:

<script type="text/javascript">
    $(document).ready(function() {
        $('#fileupload').uploadify(
            {
                'swf': "{{ asset('javascript/uploadify.swf') }}",
                'uploader': "{{ path('EasyLife_upload_avatar')}}",
                'auto': true,
                'buttonText': "Upload Avatar",
                "buttonClass": "label",
                "height": 30,
                "width": 80,
                "onUploadSuccess": function(file, data, response) {
                    alert("Successful " + file.name + " to :" + data + ":" + response);
                },
                'onUploadError' : function(file, errorCode, errorMsg, errorString) {
                    alert('The file ' + file.name + ' could not be uploaded: ' + errorString);
                }
            });
    });
</script>

这是处理上传的控制器:

public function uploadAvatarAction() {
    $user = $this->getUser();
    $user->getUsername(); // problem appears when this line is added on an Ajax call
    $targetFolder = "upload/avatar";

    return new Response($targetFolder);
}

我实际上在其他控制器的整个项目中都有$ user-&gt; getUsername(),它们都很好,即使这个也适用于直接URL调用,但是当被Ajax调用时会出现问题,有多奇怪?

有人可以帮忙吗?非常感谢!

1 个答案:

答案 0 :(得分:2)

这是因为uploadify不会随请求发送会话cookie,因此在您的控制器中$user = $this->getUser();为空。

你可以看到我遇到的类似问题here ...

您需要创建自定义会话存储...

<?php

namespace Acme\AcmeBundle\Session;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\SessionStorage\NativeSessionStorage;

class Storage extends NativeSessionStorage
{
    public function __construct(array $options = array(), ContainerInterface $container)
    {
        $request = $container->get('request');
        if ($request->query->has('sessionId')) {
            $request->cookies->set(session_name(), 1);
            session_id($request->query->get('sessionId'));
        }

        return parent::__construct($options);
    }
}

配置您的服务容器......

parameters:
    session.storage.native.class: Acme\AcmeBundle\Session\Storage
services:
    session.storage.native:
        class:     %session.storage.native.class%
        arguments: [%session.storage.options%, @service_container]