我想创建一个控制器来处理将文件上传到用户特定文件夹。我目前有一个允许用户上传将发布数据发送到控制器的文件的 from。
我希望控制器做的是获取上传的文件,并将其放在一个文件夹中,例如/public/{username}/files
但我不太确定如何使用 symfony 来处理它。
正如 Mahok 所说,Symfony2 文档在这里很有用。
我会跟着他们添加添加内容。保存文档时,传递用户名:
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”等
请注意,如果您接受空格等,您可能需要修改用户名。
编辑:您需要为用户与文件设置 oneToMany 关系,以便您以后可以找到该文件。
这可能会帮助你——
$upload_dir = "your upload directory/{username}";
if (!is_dir($upload_dir)) {
@mkdir($upload_dir, "755", true);
}
move_uploaded_file($source,$destination);