2012-12-20 27 views
0

我想创建一个控制器来处理上传文件到用户特定的文件夹。我目前有一个从那里允许用户上传一个文件,发送后数据到控制器。创建一个处理文件上传的控制器

我想控制器要做的是拿起上传的文件,并将其放置在一个文件夹,例如/public/{username}/files

但我不太清楚如何使用symfony来处理它。

+0

看看Cookbook-entry“如何处理文件上传与Doctrine”:http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html – dbrumann

+0

啊不,我没有想过,没想到关于教义,对这个哈哈还是很新的。感谢那。 – ChaoticLoki

回答

1

由于Mahok评论说,在文档的Symfony2是有用的在这里。

我会follow them与增加的补充。当您保存文档时,传递用户名:

if ($form->isValid()) { 
    $em = $this->getDoctrine()->getManager(); 
    //get the user and pass the username to the upload method 
    $user = $this->get('security.context')->getToken()->getUser(); 
    $document->upload($user->getUsername()); 

    $em->persist($document); 
    $em->flush(); 

    $this->redirect(...); 
} 

当您上传的文件,使用用户名:

public function upload($username) 
{ 
    if (null === $this->file) { 
     return; 
    } 
    //use the username for the route 
    $this->file->move(
     "/public/$username/files/", 
     $this->file->getClientOriginalName() 
    ); 

    // set the path property to the filename where you've saved the file 
    $this->path = $this->file->getClientOriginalName(); 

    // clean up the file property as you won't need it anymore 
    $this->file = null; 
} 

保存这样说你不会真正需要使用额外的实体的方法,如“ getAbsolutePath”等

请注意,你可能有,如果你接受空间等方面slugify用户名

编辑: 您将需要设置用户对文件的oneToMany关系,以便稍后可以找到该文件。

+0

啊我不知道我可以用Doctrine来简化它,谢谢! – ChaoticLoki

0

这可以帮助你---

$upload_dir = "your upload directory/{username}";   
if (!is_dir($upload_dir)) { 
    @mkdir($upload_dir, "755", true); 
} 
move_uploaded_file($source,$destination);