在Symfony 4应用程序中,用户上传的内容存储在何处?
我的网站中有一个部分,用户可以上传他们自己的个人资料图片,这些图片存储在输出目录中,并在数据库中跟踪,如下所示:在Symfony 4应用程序中,用户上传的内容存储在何处?,symfony,symfony4,Symfony,Symfony4,我的网站中有一个部分,用户可以上传他们自己的个人资料图片,这些图片存储在输出目录中,并在数据库中跟踪,如下所示: $form = $this->createForm(ProfileUpdateForm::class); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $user = $this-&g
$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/build目录是通过删除并再次创建来构建的)
如果我没有弄错的话,部署不是也是这样工作的吗?如果是这样,这是上传图像的正确方式吗?正确的做法是什么?我不知道为什么,但是你的
public/
目录不应该被删除。如果您使用的是Webpack Encore,则编译资产时会删除并再次创建
public/build/
内容。但不是public/
本身
对于上传,我们创建public/upload/
目录。然后,在大多数情况下,我们设置了一些全局变量,这允许我们只保存文件名 在
config/packages/Twig.yaml
中,哪个“根”将位于您的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/
,并且数据库中不会有任何更改,也不必保存额外的路径
只需创建一个新的全局应用程序_ul_img_缩略图
,即可设置
然后,您所要做的就是在需要时调用globals,并与文件名联系:
细枝:
{{ app_ul_avatar~dbResult.filename }}
或在控制器中:
$this->getParameter('app_ul_avatar').$dbResult->getFilename();
这到底是怎么一个基于观点的问题lol?很明显,我做的是错误的,因为我是新来的Symfony。你说的公众没有被破坏(只是构建),我说错了,并且修复了我的问题。现在让我试试这个!我确实有一个问题,我确实做了
{{app.ul.avatar}
并且我得到了一个错误,属性“ul”和方法“ul()”、“getul()”/“isul()”/“hasul()”或“uuuu call()”都不存在,并且在类“Symfony\Bridge\Twig\AppVariable”中有公共访问权。
这意味着什么?Twig很可能认为这是一个数组。我更新了我的答案以避免这个问题@Majo0od