【发布时间】:2018-04-02 02:32:57
【问题描述】:
在 Symfony 4 中,我收到此错误: 调用字符串上的成员函数guessExtension() 在以前,我使用相同的代码上传图像并且做得很好,但是在这里我遇到了错误。 有没有人遇到过同样的问题并解决了?
$em = $this->getDoctrine()->getManager();
$imageEn = new Image();
$form = $this->createForm(ImageUploadType::class, $imageEn);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
/** @var Symfony\Component\HttpFoundation\File\UploadedFile $file */
$file = $imageEn->getImage();
$fileName = md5(uniqid()).'.'.$file->guessExtension();
$file->move($this->getParameter('image_directory'), $fileName);
$imageEn->setImage($fileName);
$em->persist($imageEn);
$em->flush();
$this->addFlash('notice', 'Post Submitted Successfully!!!');
return $this->redirectToRoute('image_upload');
}
表格:
{
$builder
->add('title', TextType::class)
->add('description', TextType::class)
->add('image', FileType::class, array('label'=>'Upload Image'))
->add('submit', SubmitType::class)
;
}
图像类:
实际上我是按照他手动制作这个类的教程进行的,但是我使用命令来创建类,我将他所有的代码与我的代码进行了对比,结果是正确的。
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ORM\Entity(repositoryClass="App\Repository\ImageRepository")
*/
class Image
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
*/
private $title;
/**
* @ORM\Column(type="string", length=255)
*/
private $description;
/**
* @ORM\Column(type="string", length=255)
* @Assert\NotBlank(message="Please upload image")
* @Assert\File(mimeTypes={"image/jpeg"})
*/
private $image;
public function getId()
{
return $this->id;
}
public function getTitle(): ?string
{
return $this->title;
}
public function setTitle(string $title): self
{
$this->title = $title;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(string $description): self
{
$this->description = $description;
return $this;
}
public function getImage(): ?string
{
return $this->image;
}
public function setImage(string $image): self
{
$this->image = $image;
return $this;
}
}
【问题讨论】:
-
您的
$request对象中有什么?你看到里面有文件吗? -
不,它只是公共函数 indexAction(Request $request){}
-
不,我的意思是,当您
dump($request->files)时,您看到其中的文件了吗?其次,当您调用getImage()方法时,您的Image类应该返回什么(一个对象,一个字符串?) -
显示的是 c/xampp/tmp/php3773.tmp
-
好的,所以你正确地发布了一个文件,但是当你调用
getImage()时你的Image对象返回一个字符串。你能告诉我们你的方法createForm()好吗?