我有ActivityFile
实体应该处理文件:
class ActivityFile {
// all properties / setters / getters and so on
public function upload()
{
foreach($this->uploadedFiles as $uploadedFile) {
$fileName = md5(uniqid()) . '.' . $uploadedFile->getClientOriginalName();
$uploadedFile->move(
$this->getUploadRootDir(),
$fileName
);
$this->path = $fileName;
$this->name = $uploadedFile->getClientOriginalName();
$this->setRealPath($this->getUploadDir() . '/' . $fileName);
$this->file = null;
}
}
工作正常。我将所有上传的文件都放在所需的文件夹中。
问题是,我没有在数据库中获取数据。因为我的控制器:
class DashboardController extends Controller
{
public function indexAction(Request $request)
{
$activityFile = new ActivityFile();
$activityFile->setUser($this->getUser());
$form = $this->createFormBuilder($activityFile)
->add('uploadedFiles', FileType::class, array(
'multiple' => true,
'data_class' => null,
))
->add('save', SubmitType::class, array('label' => 'Upload'))
->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
// here is PROBLEM
// $activityFile only contains the last file
// from selected upload files
$activityFile->upload();
$em->persist($activityFile);
$em->flush();
return $this->redirect($this->generateUrl('dashboard'));
}
return $this->render('ACMEBundle:Dashboard:index.html.twig', array(
'form' => $form->createView(), 'activityFile' => $activityFile
));
}
}
如何为每个上传的文件执行数据库输入?
答案 0 :(得分:2)
您将所有上传的文件移动到目标目录,但此操作的结果存储在不是数组但是字符串的属性中。你只需每次都覆盖它。
$this->path = $fileName;
将ActivityFile的结构更改为存储文件列表,而不仅仅是一个。
否则,使用集合表单类型http://symfony.com/doc/current/reference/forms/types/collection.html
为每个上传的文件创建多个ActivityFiles