dsgft1486 2013-08-14 08:50
浏览 67
已采纳

处理Symfony 2中的plupload文件上传

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.

  • 写回答

1条回答 默认 最新

  • duanhua9398 2013-08-14 10:12
    关注

    First of all, try to use the Symfony2 way of accessing request parameters. You can get more information in the book.

    When uploading a file, Symfony2 automatically creates an instance of UploadedFile for you and puts it in a FileBag in the request object.

    You can access the files in your controller like this:

    $files = $request->files;
    

    Like said previously, these are temporary files. To upload them in a user defined directory, use the move method on the object.

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

    The variable $files now contains an instance of File.


    On the other hand, you can also use a bundle that supports the Plupload uploader. I'd recommend the OneupUploaderBundle. (Note: I'm the main developer of this bundle, I guess this needs to be added).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式
  • ¥50 关于多次提交POST数据后,无法获取到POST数据参数的问题
  • ¥15 win10,这种情况怎么办
  • ¥15 如何在配置使用Prettier的VSCode中通过Better Align插件来对齐等式?(相关搜索:格式化)
  • ¥100 在连接内网VPN时,如何同时保持互联网连接
  • ¥15 MATLAB中使用parfor,矩阵Removal的有效索引在parfor循环中受限制
  • ¥20 Win 10 LTSC 1809版本如何无损提升到20H1版本
  • ¥50 win10 LTSC 虚拟键盘不弹出
  • ¥30 微信小程序请求失败,网页能正常带锁访问
  • ¥15 Matlab求解微分方程,如何用fish2d进行预优?