Не могли бы вы помочь мне решить эту проблему? Я пробовал этот учебник: Symfony UploadSymfony2 Загрузить/Не удается сохранить в папку
Он отлично работает (сохраняется в пути базы данных к img), но не сохраняет и не перемещает изображение в папку.
Entity:
<?php
namespace DbBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\UploadedFile;
/**
* @ORM\Entity
* @ORM\HasLifecycleCallbacks
*/
class File
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
public $id;
/**
* @ORM\Column(type="string", length=255)
* @Assert\NotBlank
*/
public $name;
/**
* @ORM\Column(type="string", length=255, nullable=true)
*/
public $path;
/**
* @Assert\File(maxSize="6000000")
*/
private $file;
private $temp;
/**
* Sets file.
*
* @param UploadedFile $file
*/
public function setFile(UploadedFile $file = null)
{
$this->file = $file;
// check if we have an old image path
if (isset($this->path)) {
// store the old name to delete after the update
$this->temp = $this->path;
$this->path = null;
} else {
$this->path = 'initial';
}
}
/**
* @ORM\PrePersist()
* @ORM\PreUpdate()
*/
public function preUpload()
{
if (null !== $this->getFile()) {
// do whatever you want to generate a unique name
$filename = sha1(uniqid(mt_rand(), true));
$this->path = $filename.'.'.$this->getFile()->guessExtension();
}
}
/**
* Get file.
*
* @return UploadedFile
*/
public function getFile()
{
return $this->file;
}
/**
* @ORM\PostPersist()
* @ORM\PostUpdate()
*/
public function upload()
{
if (null === $this->getFile()) {
return;
}
// if there is an error when moving the file, an exception will
// be automatically thrown by move(). This will properly prevent
// the entity from being persisted to the database on error
$this->getFile()->move($this->getUploadRootDir(), $this->path);
// check if we have an old image
if (isset($this->temp)) {
// delete the old image
unlink($this->getUploadRootDir().'/'.$this->temp);
// clear the temp image path
$this->temp = null;
}
$this->file = null;
}
/**
* @ORM\PostRemove()
*/
public function removeUpload()
{
$file = $this->getAbsolutePath();
if ($file) {
unlink($file);
}
}
public function getAbsolutePath()
{
return null === $this->path
? null
: $this->getUploadRootDir().'/'.$this->path;
}
public function getWebPath()
{
return null === $this->path
? null
: $this->getUploadDir().'/'.$this->path;
}
protected function getUploadRootDir()
{
// the absolute directory path where uploaded
// documents should be saved
return __DIR__.'/../../../../web/'.$this->getUploadDir();
}
protected function getUploadDir()
{
// get rid of the __DIR__ so it doesn't screw up
// when displaying uploaded doc/image in the view.
return 'uploads/documents';
}
}
Контроллер:
public function uploadAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$document = new File();
$form = $this->createFormBuilder($document)
->add('name')
->add('file')
->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
$em->persist($document);
$em->flush();
return $this->redirectToRoute('web_portal_file');
}
return $this->render('WebPortalBundle:Default:file.html.twig',array('file_form' => $form->createView()));
}
EDIT: Twig:
<form action="{{ path('web_portal_file') }}" method="post" {{ form_enctype(file_form) }}>
{{ form_widget(file_form.file) }}
{{ form_rest(file_form) }}
<input type="submit"/>
</form>
Я не знаю Ва чтобы сделать эту работу. Каждый раз, когда путь будет сохранен в базе данных, но папка пуста ...
Есть ли правильные разрешения на доступ к папке для пользователя веб-сервера? – malcolm
yes,/web/uploads/documents chmod 0777 для пользователя. –
Вы проверили, возвращает ли метод 'getUploadRootDir()' правильный путь? –