问题
In Symfony 4 I'm getting this error: Call to a member function guessExtension() on string In previous I used same code to upload image and doing well, but here i'm getting error. Has anyone faced the same issue and solved?
$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');
}
Form:
{
$builder
->add('title', TextType::class)
->add('description', TextType::class)
->add('image', FileType::class, array('label'=>'Upload Image'))
->add('submit', SubmitType::class)
;
}
Image Class:
Actually I followed a tutorial where he made this class manually but I used Command to create class, I tallied all his code with mine and it was correct.
<?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;
}
}
回答1:
Replace
$file = $imageEn->getImage()
with
$file = $form->get('image')->getData();
回答2:
For me it was the typehinting of the entity that messed things up:
// I had to change this:
public function getImage(): ?string {}
public function setImage(string $image): self {}
// To this (both without 'string'):
public function getImage() {}
public function setImage( $image): self {}
来源:https://stackoverflow.com/questions/49604601/call-to-a-member-function-guessextension-on-string