0

I'm trying to write a controller to accept file uploads from the Plupload plugin. As an added bit of fun, the uploads are coming from a different URL so I have to set the Access-Control-Allow-Origin header myself. So far I've done that like so:

/**
 * @Route("/frontEnd/file/upload.{_format}")
 */
public function upload(Request $request) {
    $response = new Response();
    $response->setContent(json_encode(array('hello' => 'world')));
    $response->setStatusCode(200);
    $response->headers->set('Access-Control-Allow-Origin', '*');
    $response->send();
}

which seems to work. When I submit the uploads using plupload I see the XHR requests hit Symfony and the JSON is returned. However, I have no idea how to handle the actual file and move it into a directory.

I did a var_dump() on $_POST and it only returned the following:

array(1) {
  ["name"]=>
  string(21) "wallpaper-2873928.jpg"
}

The upload is definitely being sent as I can see the file's bytes being part of the request payload with developer tools. Do I need to use Symfony's own components to handle the upload? If so, how? The Symfony documentation only seems to cover uploading from a file upload form.

4

1 回答 1

2

首先,尝试使用 Symfony2 的方式访问请求参数。您可以在书中获得更多信息。

上传文件时,Symfony2 会自动为您创建一个UploadedFile实例,并将其放入请求对象中的FileBag中。

您可以像这样访问控制器中的文件:

$files = $request->files;

如前所述,这些是临时文件。要将它们上传到用户定义的目录中,请使用move对象上的方法。

$directory = //...

foreach ($files as $uploadedFile) {
    $name = //...
    $file = $uploadedFile->move($directory, $name);
}

该变量$files现在包含File的一个实例。


另一方面,您也可以使用支持 Plupload 上传器的包。我推荐OneuploaderBundle。(注意:我是这个捆绑包的主要开发者,我想这个需要添加)。

于 2013-08-14T10:12:30.007 回答