ユーザー固有のフォルダーへのファイルのアップロードを処理するコントローラーを作成したいと思います。私は現在、ユーザーが投稿データをコントローラーに送信するファイルをアップロードできる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);