【问题标题】:How do I upload picture with Symfony?如何使用 Symfony 上传图片?
【发布时间】:2021-08-02 03:43:41
【问题描述】:

我的实体看起来像这样

<?php

namespace App\Entity;

use App\Repository\AnimauxRepository;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass=AnimauxRepository::class)
 */
class Animaux
{
    // ...
    /**
     * @ORM\Column(type="string")
     */
    private $photo;

    // ...

    
    public function getPhoto()
    {
        return $this->photo;
    }

    public function setPhoto($photo)
    {
        $this->photo = $photo;

        return $this;
    }

    // ...
}

我的 AnimauxType.php 是这样的

<?php
// AnimauxType.php
namespace App\Form;

use App\Entity\Animaux;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints\File;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;

class AnimauxType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            // ...
            ->add('photo', FileType::class, [
                'data_class'=>null,
                'label' => 'Photo (jpg ou png)',

                'mapped' => false,

                'required' => false,

                'constraints' => [
                    new File([
                        'maxSize' => '1024k',
                        'mimeTypes' => [
                            'image/jpg',
                            'image/jpeg',
                            'image/png',
                            'image/gif',
                            'image/jfif',
                        ],
                        'mimeTypesMessage' => 'Please upload a valid image',
                    ])
                ],
            ])
            // ...
        ;
    }


    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver -> setDefault('data_class', Animaux::class);
    }
}

我的 AnimauxController.php 是这样的

public function new(Request $request, SluggerInterface $slugger): Response
    {
        $animaux = new Animaux();
        $form = $this->createForm(AnimauxType::class, $animaux);
        $form->handleRequest($request);
        
        
        if ($form->isSubmitted() && $form->isValid()) {
             /** @var UploadedFile $photo */
            $photo = $form->get('photo')->getData();

            if ($photo) {
                $originalFilename = pathinfo($photo->getClientOriginalName(), PATHINFO_FILENAME);
                $safeFilename = $slugger->slug($originalFilename);
                $newFilename = $safeFilename.'-'.uniqid().'.'.$photo->guessExtension();

                try {
                    $photo->move(
                        $this->getParameter('photo_directory'),
                        $newFilename
                    );
                } catch (FileException $e) {
                    // ... handle exception if something happens during file upload
                }

                
                $animaux->setPhoto(
                    new File($this->getParameter('photo_directory').'/'.$animaux->getPhoto())
                );
            }

            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($animaux);
            $entityManager->flush();

            return $this->redirectToRoute('animaux_index');
        }

最后我在 service.yaml 中添加了这个

parameters:
     photo_directory: '%kernel.project_dir%/public/uploads/photos'

当我尝试在表单中上传图片时,我没有收到任何错误,但我看不到图片。这是我尝试显示图片&lt;img src="{{asset('uploads/photo/' ~ animaux.photo)}}" alt=""&gt;的方法,但是当我查看代码时,我得到了 &lt;img src="/petandconnect/public/uploads/photo/C:\Users\...\Temp\php4EA9.tmp" alt=""&gt; 不能对此做出正面或反面。

【问题讨论】:

  • $newFilename 而不是 $animaux-&gt;getPhoto() ?
  • 尝试使用`vichuploader',非常好用,这里有个链接可以帮助Upload files in Symfony form
  • @Justine 请不要标记“已解决”或在问题中添加解决方案。您可以在答案部分发表评论或添加答案。在提出其他问题之前不要忘记阅读帮助中心,它将帮助您更快地获得帮助。

标签: symfony file-upload upload


【解决方案1】:

在这种情况下,[VichUploaderBundle] 将成为您的朋友。您的浏览器无法识别直接来自数据库的文件的相对路径。您将需要另一个 File 类型的属性 photoFile,它将与您的属性“photo”进行映射。

只需使用 VichUpploaderBundle 谷歌该过程,它就会起作用。它是社区批准的用于上传文件的捆绑包。另外,不要忘记使用 cacheManager 从缓存中删除以前的照片,否则您的应用会变慢。

【讨论】:

    猜你喜欢
    • 2015-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-06
    • 1970-01-01
    • 2016-11-22
    • 2020-11-13
    相关资源
    最近更新 更多