我想創建一個控制器來處理上傳文件到用戶特定的文件夾。我目前有一個從那裏允許用戶上傳一個文件,發送後數據到控制器。創建一個處理文件上傳的控制器
我想控制器要做的是拿起上傳的文件,並將其放置在一個文件夾,例如/public/{username}/files
但我不太清楚如何使用symfony來處理它。
我想創建一個控制器來處理上傳文件到用戶特定的文件夾。我目前有一個從那裏允許用戶上傳一個文件,發送後數據到控制器。創建一個處理文件上傳的控制器
我想控制器要做的是拿起上傳的文件,並將其放置在一個文件夾,例如/public/{username}/files
但我不太清楚如何使用symfony來處理它。
由於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關係,以便稍後可以找到該文件。
啊我不知道我可以用Doctrine來簡化它,謝謝! – ChaoticLoki
這可以幫助你---
$upload_dir = "your upload directory/{username}";
if (!is_dir($upload_dir)) {
@mkdir($upload_dir, "755", true);
}
move_uploaded_file($source,$destination);
看看Cookbook-entry「如何處理文件上傳與Doctrine」:http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html – dbrumann
啊不,我沒有想過,沒想到關於教義,對這個哈哈還是很新的。感謝那。 – ChaoticLoki