我的站点中有一个部分,用户可以在其中上传自己的个人资料图片,这些图片存储在输出目录中,并在数据库中进行跟踪,如下所示:
$form = $this->createForm(ProfileUpdateForm::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
$user = $this->getUser();
$firstname = $form->get('firstname')->getData();
$lastname = $form->get('lastname')->getData();
$picture = $form->get('profilepicture')->getData();
if($picture == null)
{
$user
->setFirstName($firstname)
->setLastName($lastname);
}
else
{
$originalFilename = pathinfo($picture->getClientOriginalName(), PATHINFO_FILENAME);
// this is needed to safely include the file name as part of the URL
$safeFilename = strtolower(str_replace(' ', '', $originalFilename));
$newFilename = $safeFilename.'-'.uniqid().'.'.$picture->guessExtension();
try {
$picture->move(
'build/images/user_profiles/',
$newFilename
);
} catch (FileException $e) {
$this->addFlash("error", "Something happened with the file upload, try again.");
return $this->redirect($request->getUri());
}
// updates the 'picture' property to store the image file name
// instead of its contents
$user
->setProfilePicture($newFilename)
->setFirstName($firstname)
->setLastName($lastname);
}
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($user);
$entityManager->flush();
$this->addFlash("success", "Your profile was updated!");
return $this->redirectToRoute('account');
}
return $this->render('account/profile.html.twig', [
'profileform' => $form->createView()
]);
我发现的问题是,每次编译本地项目时,都会删除该映像(因为通过删除并重新创建来建立公共目录)。
如果我没记错的话,这也不就是部署的工作方式吗?如果是的话,那是上传图片的正确方法吗?解决此问题的正确方法是什么?
public/
目录。如果您使用的是Webpack Encore,则在编译资产时会删除public/build/
内容并再次创建。但不是public/
本身。对于上传,我们创建public/upload/
目录。然后,大多数时候,我们设置一些全局变量,这些全局变量只允许保存文件名。
config/packages/twig.yaml
中的Twig的全局变量,其中“根”将位于您的public/
目录中
twig:
globals:
app.ul.avatar: '/upload/avatar/'
app.ul.document: '/upload/document/'
以及config/services.yaml
中控制器和存储库等的全局变量>
parameters: app.ul.avatar: '%kernel.root_dir%/../public/upload/avatar/' app.ul.document: '%kernel.root_dir%/../public/upload/document/'
这很方便,因为正如我刚才所说,您只能将文件名保存在数据库中。这意味着,如果您有一个
public/upload/img/
文件夹,并且还希望生成缩略图,则可以创建public/upload/img/thumbnail/
,而数据库中的内容将保持不变,也不必保存额外的路径。只需创建一个新的全局
app.ul.img.thumbnail
,就设置好了。然后,您要做的就是在需要时调用全局变量,并使用文件名联系:
在树枝上:
{{ app.ul.avatar~dbResult.filename }}
或在控制器中:
$this->getParameter('app.ul.avatar').$dbResult->getFilename();