在 Symfony 4 中上传图片

Upload image in Symfony 4

我正在尝试使用本教程在我的 Symfony 项目中上传文件: http://symfony.com/doc/current/controller/upload_file.html

Symfony 没有显示错误,但是当我上传文件时没有任何反应,在我的数据库中没有 filename.jpg 我有这一行 C:\wamp64\tmp\php9294.tmp

这是我的实体:

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\File;

/**
* @ORM\Entity(repositoryClass="App\Repository\ItemRepository")
*/
class Item
{
/**
 * @ORM\Id()
 * @ORM\GeneratedValue()
 * @ORM\Column(type="integer")
 */
private $id;

/**
 * @ORM\Column(type="string")
 * @Assert\NotBlank(message="Upload your image")
 * @Assert\File(mimeTypes={ "image/png", "image/jpeg" })
 */
private $image;

public function getImage()
{
    return $this->image;
}

public function setImage($image)
{
    $this->image = $image;

    return $this;
}

我的表格:

namespace App\Form;

use App\Entity\Item;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\FileType;


class ItemType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('image',FileType::class,array('data_class'=> null, 'label' => 'Image'))
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => Item::class,
        ));
    }
}

我的控制器:

namespace App\Controller;

use App\Entity\Item;
use App\Form\ItemType;
use App\Repository\ItemRepository;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

/**
 * @Route("/item")
 */
class ItemController extends Controller
{
    /**
     * @Route("/", name="item_index", methods="GET")
     */

    /**
     * @Route("/new", name="item_new", methods="GET|POST")
     */
    public function new(Request $request): Response
    {
        $item = new Item();
        $form = $this->createForm(ItemType::class, $item);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $file = $item->getImage();

            $fileName = $this->generateUniqueFileName().'.'.$file->guessExtension();

            // moves the file to the directory where brochures are stored
            $file->move(
                $this->getParameter('brochures_directory'),
                $fileName
            );

            $item->setImage($fileName);



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

        return $this->render('item/new.html.twig', [
            'item' => $item,
            'form' => $form->createView(),
        ]);
    }

    /**
     * @return string
     */
    private function generateUniqueFileName()
    {
        // md5() reduces the similarity of the file names generated by
        // uniqid(), which is based on timestamps
        return md5(uniqid());
    }
}

我完全按照教程中的步骤操作,但我的文件夹中似乎没有上传图片

我建议您使用 StofDoctrineExtensionsBundle:https://symfony.com/doc/master/bundles/StofDoctrineExtensionsBundle/index.html

上传扩展是给你的,是帮助你上传文件的一些服务。

首先,要求它:composer require stof/doctrine-extensions-bundle
现在,像这样在文件 config/packages/stof_doctrine_extensions.yml 中配置它(考虑到文件夹 public/uploads 是使用 read/write 权限创建的):

stof_doctrine_extensions:
    default_locale: en_US
    uploadable:
        default_file_path: "%kernel.root_dir%/../public/uploads"
        mime_type_guesser_class: Stof\DoctrineExtensionsBundle\Uploadable\MimeTypeGuesserAdapter
        default_file_info_class: Stof\DoctrineExtensionsBundle\Uploadable\UploadedFileInfo
    orm:
        default:
            uploadable: true

现在,创建 Entity/File.php 以供使用:

<?php

namespace App\Entity;

use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation as Serializer;
use Overblog\GraphQLBundle\Annotation\GraphQLColumn;

/**
 * @ORM\Entity
 * @Gedmo\Uploadable(filenameGenerator="SHA1", allowOverwrite=true, appendNumber=true)
 */
class File
{
    /**
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    protected $id;

    /**
     * @ORM\Column(name="path", type="string")
     * @Gedmo\UploadableFilePath
     */
    protected $path;

    /**
     * @ORM\Column(name="name", type="string")
     * @Gedmo\UploadableFileName
     */
    protected $name;

    /**
     * @ORM\Column(name="mime_type", type="string")
     * @Gedmo\UploadableFileMimeType
     */
    protected $mimeType;

    /**
     * @ORM\Column(name="size", type="decimal")
     * @Gedmo\UploadableFileSize
     */
    protected $size;

    /**
     * @GraphQLColumn(type="String")
     */
    protected $publicPath;

    /**
     * @return string
     */
    public function getPublicPath()
    {
        return '/uploads/'.$this->name;
    }

    /**
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @return mixed
     */
    public function getPath()
    {
        return $this->path;
    }

    /**
     * @param mixed $path
     *
     * @return File
     */
    public function setPath($path)
    {
        $this->path = $path;

        return $this;
    }

    /**
     * @return mixed
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @param mixed $name
     *
     * @return File
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * @return mixed
     */
    public function getMimeType()
    {
        return $this->mimeType;
    }

    /**
     * @param mixed $mimeType
     *
     * @return File
     */
    public function setMimeType($mimeType)
    {
        $this->mimeType = $mimeType;

        return $this;
    }

    /**
     * @return mixed
     */
    public function getSize()
    {
        return $this->size;
    }

    /**
     * @param mixed $size
     *
     * @return File
     */
    public function setSize($size)
    {
        $this->size = $size;

        return $this;
    }
}

最后一步是创建文件实体的关系。之后,您可以使用 UploadManager 来具体化上传:

<?php

public function uploadFile(\Stof\DoctrineExtensionsBundle\Uploadable\UploadableManager $uploadableManager)
{
    $uploadableManager->markEntityToUpload($file, $fileInfo);
}

而且只是 persist/flush 它。

我也遇到了同样的问题,后来发现是权限的问题,如果其他人卡在这部分,给文件夹所有权限再试一次。

希望对您有所帮助。