How to upload and save image without bundle in Symfony 4 - image

I have a user entity that has an image property. When I register a user from a registration form, the image is displayed in the user's profile view and the name of the image is saved in the database. But when I want to change the profile of the user from an edit form, when sending the form, I have the following message: the file was not found
/**
* #ORM\Column(type="string", length=255, nullable=true)
* #Assert\File(mimeTypes={ "image/jpeg" })
*/
private $picture;
private $file;
```entity User methods
/**
* Get the value of file
*/
public function getFile()
{
return $this->file;
}
/**
* Set the value of file
*
* #return self
*/
public function setFile($file)
{
$this->file = $file;
return $this;
}
``` the method in the AccountController
/**
* Permet d'afficher le formulaire d'édition du profil
* #Route("/account/profile", name="account_profile")
*
* #return Response
*/
public function profile(Request $request, ObjectManager $manager)
{
$user = $this->getUser();
$form = $this->createForm(AccountType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$user->setPicture(
new File($this->getParameter('upload_directory') . '/' . $user->getPicture())
);
$manager->persist($user);
$manager->flush();
$this->addFlash(
'success',
"Les modifications ont bien été enregistrées"
);
return $this->redirectToRoute('user_show');
}
return $this->render('account/profile.html.twig', [
'form' => $form->createView()
]);
}
I also created a pictureUploadListener entity that I declared in the service.yaml file

Related

How to get file extension from SwiftAttachment object in Laravel Email Transport

This is Laravel 8. I'm extending Illuminate\Mail\Transport\Transport class to create a custom mail transport in order to utilize the company's custom mail API with Illuminate\Mail\Mailable. I got most of it working, including file attachments, however the Swift_Mime_SimpleMimeEntity and the classes deriving from it contain getBody(), getFilename(), getSize(), and getContentType() but no methods to extract file extension.
<?php
namespace App\CustomMailDriver;
use GuzzleHttp\ClientInterface;
use Illuminate\Mail\Transport\Transport;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Swift_Mime_SimpleMessage;
class CustomTransport extends Transport
{
/**
* Guzzle client instance.
*
* #var \GuzzleHttp\ClientInterface
*/
protected $client;
/**
* API key.
*
* #var string
*/
protected $key;
/**
* The API URL to which to POST emails.
*
* #var string
*/
protected $url;
/**
* Create a new Custom transport instance.
*
* #param \GuzzleHttp\ClientInterface $client
* #param string|null $url
* #param string $key
* #return void
*/
public function __construct(ClientInterface $client, string $url, string $key)
{
$this->key = $key;
$this->client = $client;
$this->url = $url;
}
/**
* {#inheritdoc}
*/
public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null)
{
$this->beforeSendPerformed($message);
$payload = $this->getPayload($message);
try {
// ignore ssl (esp when working in DEV/QA)
$response = Http::withoutVerifying()->withHeaders([
'X-Authorization' => $this->key
])->post($this->url, $payload);
Log::info($response->body());
} catch (\Exception $e) {
Log::error($e->getMessage());
}
$this->sendPerformed($message);
return $this->numberOfRecipients($message);
}
/**
* Get the HTTP payload for sending the message.
*
* #param \Swift_Mime_SimpleMessage $message
* #return array
*/
protected function getPayload(Swift_Mime_SimpleMessage $message): array
{
// to
if (!empty($message->getTo())) {
$payload['payload']['to']['email'] = key($message->getTo());
}
// cc
if (!empty($message->getCc())) {
$payload['payload']['cc']['email'] = key($message->getCc());
}
// bcc
if (!empty($message->getBcc())) {
$payload['payload']['bcc']['email'] = key($message->getBcc());
}
// subject
$payload['payload']['subject'] = $message->getSubject();
// html
$payload['payload']['message']['html'] = $message->getBody();
// message children contains plain text, attachments, etc
$children = $message->getChildren();
if (!empty($children)) {
foreach($children as $child) {
// attachments
if (get_class($child) === 'Swift_Attachment') {
$payload['payload']['attachments'][] = [
'content' => base64_encode($child->getBody()),
'filename' => $child->getFilename(),
];
}
// plain text
if (get_class($child) === 'Swift_MimePart') {
$payload['payload']['message']['text'] = $child->getBody();
}
}
}
return $payload;
}
}
I had to go different route. Instead of searching the extension inside Transport class using Swift_Mime_SimpleMessage, I passed the filename with the original extension to Transport class from Illuminate\Mail\Mailable
public function build()
{
$tempUpload = request()->file('file_attachment');
$filename = $tampUpload->getClientOriginalName() . "." . $tempUpload->getClientOriginalExtension();
return $this->from($this->from_email, $this->from_name)
->subject('subject line')
->attach($tempUpload, ['as' => $filename)
->view('emails.gce.supplier_supplier')
->with($this->data);
}

option to send copy of customer welcome email to another address mail in magento 2

i need to send a copy of welcome email to specific mail.
what i did is i tried to create module to do it programmatically, i created a overrid that handle execute CreatePost.php but it sent before.
<?php
/**
* Copyright © Cinemanext, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Cinemanext\ForceLogin\Controller\Account;
use \Magento\Framework\App\ObjectManager;
/**
* #SuppressWarnings(PHPMD.TooManyFields)
* #SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class CreatePost extends \Magento\Customer\Controller\Account\CreatePost
{
}
this option exist in order mail, you can send copy to specific email.
how i can add same function to welcome mail.
Try below code
<?php
namespace Cinemanext\ForceLogin\Controller\Account;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Customer\Model\CustomerFactory;
use Magento\Customer\Model\AddressFactory;
use Magento\Framework\Message\ManagerInterface;
use Magento\Framework\Escaper;
use Magento\Framework\UrlFactory;
use Magento\Customer\Model\Session;
use Magento\Customer\Model\Registration;
use Magento\Framework\Data\Form\FormKey\Validator;
use Magento\Framework\App\ObjectManager;
class CreatePost extends \Magento\Framework\App\Action\Action
{
/**
* #var \Magento\Store\Model\StoreManagerInterface
*/
protected $storeManager;
/**
* #var \Magento\Customer\Model\CustomerFactory
*/
protected $customerFactory;
/**
* #var \Magento\Customer\Model\AddressFactory
*/
protected $addressFactory;
/**
* #var \Magento\Framework\Message\ManagerInterface
*/
protected $messageManager;
/**
* #var \Magento\Framework\Escaper
*/
protected $escaper;
/**
* #var \Magento\Framework\UrlFactory
*/
protected $urlFactory;
/**
* #var \Magento\Customer\Model\Session
*/
protected $session;
/**
* #var Magento\Framework\Data\Form\FormKey\Validator
*/
private $formKeyValidator;
/**
* #param Context $context
* #param StoreManagerInterface $storeManager
* #param CustomerFactory $customerFactory
* #param AddressFactory $addressFactory
* #param ManagerInterface $messageManager
* #param Escaper $escaper
* #param UrlFactory $urlFactory
* #param Session $session
* #param Validator $formKeyValidator
*/
public function __construct(
Context $context,
StoreManagerInterface $storeManager,
CustomerFactory $customerFactory,
AddressFactory $addressFactory,
ManagerInterface $messageManager,
Escaper $escaper,
UrlFactory $urlFactory,
Session $session,
Validator $formKeyValidator = null
)
{
$this->storeManager = $storeManager;
$this->customerFactory = $customerFactory;
$this->addressFactory = $addressFactory;
$this->messageManager = $messageManager;
$this->escaper = $escaper;
$this->urlModel = $urlFactory->create();
$this->session = $session;
$this->formKeyValidator = $formKeyValidator ?: ObjectManager::getInstance()->get(Validator::class);
// messageManager can also be set via $context
// $this->messageManager = $context->getMessageManager();
parent::__construct($context);
}
/**
* Default customer account page
*
* #return void
*/
public function execute()
{
/** #var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
// if ($this->session->isLoggedIn() || !$this->registration->isAllowed()) {
// $resultRedirect->setPath('*/*/');
// return $resultRedirect;
// }
// check if the form is actually posted and has the proper form key
if (!$this->getRequest()->isPost() || !$this->formKeyValidator->validate($this->getRequest())) {
$url = $this->urlModel->getUrl('*/*/create', ['_secure' => true]);
$resultRedirect->setUrl($this->_redirect->error($url));
return $resultRedirect;
}
$websiteId = $this->storeManager->getWebsite()->getWebsiteId();
$firstName = 'John';
$lastName = 'Doe';
$email = 'johndoe4#example.com';
$password = 'Test1234';
// instantiate customer object
$customer = $this->customerFactory->create();
$customer->setWebsiteId($websiteId);
// check if customer is already present
// if customer is already present, then show error message
// else create new customer
if ($customer->loadByEmail($email)->getId()) {
//echo 'Customer with the email ' . $email . ' is already registered.';
$message = __(
'There is already an account with this email address "%1".',
$email
);
// #codingStandardsIgnoreEnd
$this->messageManager->addError($message);
} else {
try {
// prepare customer data
$customer->setEmail($email);
$customer->setFirstname($firstName);
$customer->setLastname($lastName);
// set null to auto-generate password
$customer->setPassword($password);
// set the customer as confirmed
// this is optional
// comment out this line if you want to send confirmation email
// to customer before finalizing his/her account creation
$customer->setForceConfirmed(true);
// save data
$customer->save();
// save customer address
// this is optional
// you can skip saving customer address while creating the customer
$customerAddress = $this->addressFactory->create();
$customerAddress->setCustomerId($customer->getId())
->setFirstname($firstName)
->setLastname($lastName)
->setCountryId('US')
->setRegionId('12') // optional, depends upon Country, e.g. USA
->setRegion('California') // optional, depends upon Country, e.g. USA
->setPostcode('90232')
->setCity('Culver City')
->setTelephone('888-888-8888')
->setFax('999')
->setCompany('XYZ')
->setStreet(array(
'0' => 'Your Customer Address 1', // compulsory
'1' => 'Your Customer Address 2' // optional
))
->setIsDefaultBilling('1')
->setIsDefaultShipping('1')
->setSaveInAddressBook('1');
try {
// save customer address
$customerAddress->save();
} catch (Exception $e) {
$this->messageManager->addException($e, __('We can\'t save the customer address.'));
}
// send welcome email to the customer
$customer->sendNewAccountEmail();
//echo 'Customer with the email ' . $email . ' is successfully created.';
$this->messageManager->addSuccess(
__(
'Customer account with email %1 created successfully.',
$email
)
);
$url = $this->urlModel->getUrl('*/*/create', ['_secure' => true]);
$resultRedirect->setUrl($this->_redirect->success($url));
//$resultRedirect->setPath('*/*/');
return $resultRedirect;
} catch (StateException $e) {
$url = $this->urlModel->getUrl('customer/account/forgotpassword');
// #codingStandardsIgnoreStart
$message = __(
'There is already an account with this email address. If you are sure that it is your email address, click here to get your password and access your account.',
$url
);
// #codingStandardsIgnoreEnd
$this->messageManager->addError($message);
} catch (InputException $e) {
$this->messageManager->addError($this->escaper->escapeHtml($e->getMessage()));
foreach ($e->getErrors() as $error) {
$this->messageManager->addError($this->escaper->escapeHtml($error->getMessage()));
}
} catch (LocalizedException $e) {
$this->messageManager->addError($this->escaper->escapeHtml($e->getMessage()));
} catch (\Exception $e) {
$this->messageManager->addException($e, __('We can\'t save the customer.'));
}
}
$this->session->setCustomerFormData($this->getRequest()->getPostValue());
$defaultUrl = $this->urlModel->getUrl('*/*/create', ['_secure' => true]);
$resultRedirect->setUrl($this->_redirect->error($defaultUrl));
return $resultRedirect;
}
}

Laravel 5.2.x - Intervention/Image - Call to a member function encode() on null

I have created a repository to manage the upload image using Intervention/Imagelibrary but when I try to save an image I get Call to a member function encode() on null.
This is my interface:
namespace App\Repositories\MeetMount\ImageUploader;
use Illuminate\Http\Request;
interface ImageContract {
public function getExt($filename);
public function setFolder($folderName);
public function getRandomFilename($fileName);
public function addWatermark($watermarkName);
public function resize($width, $height);
public function getFileName();
public function save(Request $file);
}
This is my concrete class:
namespace App\Repositories\MeetMount\ImageUploader;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Intervention\Image\Image;
class InterventionImageRepository implements ImageContract {
/**
* #var Image
*/
private $image;
/**
* #var $folder
*/
private $folder;
/**
* InterventionImageRepository constructor.
*
* #param Image $image
*/
public function __construct( Image $image )
{
$this->image = $image;
}
/**
* Restituisce l'estensione dell'immagine
*
* #param $fileName
* #return string
*/
public function getExt( $fileName )
{
$pos = strrpos( $fileName, '.' );
$ext = substr( $fileName, $pos, strlen( $fileName ) );
return $ext;
}
/**
* Imposta la cartella dove salvare l'immagine
*
* #param $folderName
* #return $this
*/
public function setFolder( $folderName )
{
$folderPath = public_path( $folderName );
if( ! File::exists( $folderPath ) )
{
File::makeDirectory( $folderPath );
}
$this->folder = $folderPath;
return $this;
}
public function getRandomFilename( $fileName )
{
// TODO: Implement getRandomFilename() method.
}
/**
* Aggiungi watermark
*
* #param $watermarkName
* #return $this
*/
public function addWatermark( $watermarkName )
{
$watermarkPath = public_path( 'images/watermarks/' . $watermarkName );
$this->image->insert( $watermarkPath );
return $this;
}
/**
* Salva il file
*
* #param $file
* #return $this
*/
public function save( Request $request )
{
$file = $request->file('immagine');
$fileFolder = $this->folder . '/' . $file->getClientOriginalName();
$this->image->save( $fileFolder );
return $this;
}
public function getFileName()
{
// TODO: Implement getFileName() method.
}
public function resize( $width, $height )
{
// TODO: Implement resize() method.
}
}
and this is the store method:
public function store( CreatePlaceRequest $request )
{
$this->imageRepository->setFolder('cartella-prova')->save($request);
}
When I submit the form I get:
FatalErrorException in Image.php line 119:
Call to a member function encode() on null
in Image.php line 119
at FatalErrorException->__construct() in HandleExceptions.php line 133
at HandleExceptions->fatalExceptionFromError() in HandleExceptions.php line 118
at HandleExceptions->handleShutdown() in HandleExceptions.php line 0
at Image->encode() in Image.php line 139
at Image->save() in InterventionImageRepository.php line 96
at InterventionImageRepository->save() in PlacesController.php line 80
at PlacesController->store() in Controller.php line 76
The problem should be here: at Image->save() in InterventionImageRepository.php line 96
and that line is in the concrete class, in the save method:
$this->image->save( $fileFolder );
Can someone help me to find the problem?
According to the error:
Call to a member function encode() on null ...
This means you are trying to save an image while it doesn't received an image - null.
The problem is with save function in your InterventionImageRepository class. I've modified it to check if there is an image or not.
Also consider your image filed name has typo(immagine). Make sure you use the same word in your form input feild with type=file. Else correct it to have same name both in controller/class files and frond end views. Also make sure you are using enctype="multipart/form-data" in your <form> tag.
<form method="post" action="target-path" enctype="multipart/form-data">
Otherwise files will not send to server along with the form values.
/**
* Salva il file
*
* #param $file
* #return $this
*/
public function save( Request $request )
{
//first check if the file received
if($request->hasFile('immagine')){
$file = $request->file('immagine');
$fileFolder = $this->folder . '/' . $file->getClientOriginalName();
$this->image->save( $fileFolder );
return $this;
}else{
//Do some necessary outputs here
//may be store a message to session and display it to user in the view
//or return a boolean value and check for it in your store method
}
}
Refer to this Laravel's official documentation and improve your scripts: https://laravel.com/docs/5.2/requests#files

Uploading images with symfony. The image is not saved in the correct path

I am new at Symfony. I have been trying to create a reusable form and upload an image with it. The problem is that the image it is not saved in the path i have given. I dont know what i am doing wrong. I would really appreciate any suggestion.
Entity
<?php
namespace test\TestBundle\Entity\media;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\validator\Constraints as Assert;
/**
* Media
*#ORM\Entity
* #ORM\Table(name="upload")
* #ORM\HasLifecycleCallbacks
*/
class Media
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(name="name",type="string",length=255)
* #Assert\NotBlank
*/
public $name;
/**
* #ORM\Column(name="path",type="string",length=255, nullable=true)
*/
public $path;
public $file;
/**
* #ORM\PostLoad()
*/
public function postLoad()
{
$this->updateAt = new \DateTime();
}
public function getUploadRootDir()
{
return __dir__.'/../../../../web/uploads';
}
public function getAbsolutePath()
{
return null === $this->path ? null : $this->getUploadRootDir().'/'.$this->path;
}
public function getAssetPath()
{
return 'uploads/'.$this->path;
}
/**
* #ORM\Prepersist()
* #ORM\Preupdate()
*/
public function preUpload()
{
$this->tempFile = $this->getAbsolutePath();
$this->oldFile = $this->getPath();
$this->updateAt = new \DateTime();
if (null !== $this->file)
$this->path = sha1(uniqid(mt_rand(),true)).'.'.$this->file->guessExtension();
}
/**
* #ORM\PostPersist()
* #ORM\PostUpdate()
*/
public function upload()
{
if (null !== $this->file) {
$this->file->move($this->getUploadRootDir(),$this->path);
unset($this->file);
if ($this->oldFile != null) unlink($this->tempFile);
}
}
/**
* #ORM\PreRemove()
*/
public function preRemoveUpload()
{
$this->tempFile = $this->getAbsolutePath();
}
/**
* #ORM\PostRemove()
*/
public function removeUpload()
{
if (file_exists($this->tempFile)) unlink($this->tempFile);
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
public function getPath()
{
return $this->path;
}
public function getName()
{
var_dump($this->name);
return $this->name;
}
}
Controller
namespace test\TestBundle\Controller\media;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use test\TestBundle\Entity\media\Media;
use test\TestBundle\Form\media\MediaType;
/**
* media\Media controller.
*
* #Route("/img")
*/
class MediaController extends Controller
{
/**
* Lists all media\Media entities.
*
* #Route("/", name="img")
* #Method("GET")
* #Template()
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('testTestBundle:media\Media')->findAll();
return array(
'entities' => $entities,
);
}
/**
* Creates a new media\Media entity.
*
* #Route("/", name="img_create")
* #Method("POST")
* #Template("testTestBundle:media\Media:new.html.twig")
*/
public function createAction(Request $request)
{
$entity = new Media();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('img_show', array('id' => $entity->getId())));
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Creates a form to create a media\Media entity.
*
* #param Media $entity The entity
*
* #return \Symfony\Component\Form\Form The form
*/
private function createCreateForm(Media $entity)
{
$form = $this->createForm(new MediaType(), $entity, array(
'action' => $this->generateUrl('img_create'),
'method' => 'POST',
));
$form->add('submit', 'submit', array('label' => 'Create'));
return $form;
}
/**
* Displays a form to create a new media\Media entity.
*
* #Route("/new", name="img_new")
* #Method("GET")
* #Template()
*/
public function newAction()
{
$entity = new Media();
$form = $this->createCreateForm($entity);
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Finds and displays a media\Media entity.
*
* #Route("/{id}", name="img_show")
* #Method("GET")
* #Template()
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('testTestBundle:media\Media')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find media\Media entity.');
}
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
);
}
/**
* Displays a form to edit an existing media\Media entity.
*
* #Route("/{id}/edit", name="img_edit")
* #Method("GET")
* #Template()
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('testTestBundle:media\Media')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find media\Media entity.');
}
$editForm = $this->createEditForm($entity);
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Creates a form to edit a media\Media entity.
*
* #param Media $entity The entity
*
* #return \Symfony\Component\Form\Form The form
*/
private function createEditForm(Media $entity)
{
$form = $this->createForm(new MediaType(), $entity, array(
'action' => $this->generateUrl('img_update', array('id' => $entity->getId())),
'method' => 'PUT',
));
$form->add('submit', 'submit', array('label' => 'Update'));
return $form;
}
/**
* Edits an existing media\Media entity.
*
* #Route("/{id}", name="img_update")
* #Method("PUT")
* #Template("testTestBundle:media\Media:edit.html.twig")
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('testTestBundle:media\Media')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find media\Media entity.');
}
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createEditForm($entity);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$em->flush();
return $this->redirect($this->generateUrl('img_edit', array('id' => $id)));
}
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Deletes a media\Media entity.
*
* #Route("/{id}", name="img_delete")
* #Method("DELETE")
*/
public function deleteAction(Request $request, $id)
{
$form = $this->createDeleteForm($id);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('testTestBundle:media\Media')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find media\Media entity.');
}
$em->remove($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('img'));
}
/**
* Creates a form to delete a media\Media entity by id.
*
* #param mixed $id The entity id
*
* #return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm($id)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('img_delete', array('id' => $id)))
->setMethod('DELETE')
->add('submit', 'submit', array('label' => 'Delete'))
->getForm()
;
}
}
Form
namespace test\TestBundle\Form\media;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class MediaType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('file','file', array('required' => false))
->add('name')
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'test\TestBundle\Entity\media\Media'
));
}
/**
* #return string
*/
public function getName()
{
return 'test_testbundle_media_media';
}
}
I you are playing with Symfony2 forms and file upload I'd not recommend doing it as it's described in official documentation.
Please take a look at https://github.com/dustin10/VichUploaderBundle, configure your upload, link entity and enjoy!
I think the documentation is a great example for basic file upload.
Try to update your entity like this :
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(name="name",type="string",length=255)
* #Assert\NotBlank
*/
public $name;
/**
* #ORM\Column(name="path",type="string",length=255, nullable=true)
*/
public $path;
/**
* #Assert\File(maxSize="6000000")
*/
public $file;
/**
* Sets file.
*
* #param UploadedFile $file
*/
public function setFile(UploadedFile $file = null)
{
$this->file = $file;
}
/**
* Get file.
*
* #return UploadedFile
*/
public function getFile()
{
return $this->file;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return File
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set path
*
* #param string $path
* #return File
*/
public function setPath($path)
{
$this->path = $path;
return $this;
}
/**
* Get path
*
* #return string
*/
public function getPath()
{
return $this->path;
}
public function getAbsolutePath()
{
return null === $this->path ? null : $this->getUploadRootDir().'/'.$this->path;
}
public function getWebPath()
{
return null === $this->path ? null : $this->getUploadDir().'/'.$this->path;
}
public function getUploadRootDir()
{
return __DIR__.'/../../../../web/'.$this->getUploadDir();
}
public function getUploadDir()
{
return 'uploads/documents/';
}
public function upload()
{
if (null === $this->getFile()){
return;
}
$this->getFile()->move(
$this->getUploadRootDir(),
$this->getFile()->getClientOriginalName()
);
$this->path = $this->getFile()->getClientOriginalName();
$this->file = null;
}
And in your controller, a simple upload action for GET and POST :
public function UploadAction()
{
$document = new Media();
$form = $this->createFormBuilder($document)
->add('file')
->getForm();
if ($this->getRequest()->isMethod('POST')) {
$form->handleRequest($this->getRequest());
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$account = $em->getRepository('AccountingAccountBundle:Account')->findOneBy(array('id' => $accountId));
$document->setAccount($account);
$document->upload();
$em->persist($document);
$em->flush();
}
}
return array('form' => $form->createView());
}
If this example don't work on your server, maybe you have a problem with rights in your file system.
the problem was in the path directories, just needed one more directory return dir.'/../../../../../web/uploads'; like this :)
Most simplefied idea:
Create normal form in twig,and try to use/rebuilt to your own need trait below.
I used it in some simple uploads connected to entity, it's not a great code (no file validation etc. ) , but it can be a good start for you.
$location variable is configured if trait is in entity dir
user trait below to upload (
<?php
namespace AdminBundle\Entity;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
trait LinkFileTrait
{
private $location='/../../../web/media/link' ;
private $path=__DIR__;
public function checkDir(){
$id=$this->getId();
$fs=new Filesystem();
if(!$fs->exists($this->path.$this->location))
$fs->mkdir($this->path.$this->location);
$this->setImagePath($this->path.$this->location.'/'.$id.'');
if(!$fs->exists($this->getImagePath()))
$fs->mkdir($this->getImagePath());
}
public function getImages(){
$this->checkDir();
$finder = new Finder();
return $finder->files() ->in($this->getImagePath());
}
public function getRandomImage(){
$images=$this->getImages();
$images=iterator_to_array($images);
if(count($images)<1)
return null;
shuffle($images);
return $images[0];
}
public function UploadFile(UploadedFile $file){
$file->move($this->getImagePath().'/',$file->getClientOriginalName());
}
public function removeImage($file){
$this->checkDir();
$fs=new Filesystem();
if($fs->exists($this->getImagePath().'/'.$file))
$fs->remove($this->getImagePath().'/'.$file);
}
public function imageExists($image){
$this->checkDir();
$fs=new Filesystem();
return $fs->exists($this->getImagePath().'/'.$image);
}
public function getRelativePath($path){
$path=strtr($path,"\\","/");
$x=explode('../web/',$path);
return $x[1];
}
public function getImageName($path){
$path=strtr($path,"\\","/");
$x=explode('/',$path);
return $x[count($x)-1];
}
public function getFileName($path){
$x=explode('/',$path);
return $x[count($x)-1];
}
}
and in your controller
public function imagesAction(Link $link,Request $request)
{
$link->checkDir();
$images=$link->getImages();
if($request->getMethod()=='POST'){
$file=$request->files->all()['plik'];
$link->UploadFile($file);
}
return array('link'=>$link,'images'=>$images);
}

Symfony2 Image file upload

I am trying to handle image uploads via a form and then display these image uploads elsewhere in my website.
So far I have been looking at the Cookbook and also at other tutorials.I have created an Entity and a Form and am able to submit , but I am not sure if I am storing the file itself in my DB or just the name of it.
When I try to display the images in my view resource not found error on the images. Any suggestions on the correct way to upload images in Symfony?
and this is what I have so far. Entity
<?php
namespace BlogBundle\Entity;
use Symfony\Component\HttpFoundation\File\File;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Photo
*
*
* #ORM\Entity
* #ORM\HasLifecycleCallbacks
*/
class Upload
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
*Image File
* #var File
* #Assert\File( maxSize = "5M",mimeTypes = {"image/jpeg", "image/gif", "image/png", "image/tiff"}, mimeTypesMessage = "Please upload a valid Image")
*
*/
private $file;
/**
* #ORM\Column(type="string", length=500)
*/
private $title;
/**
* #ORM\Column(type="string", length=500)
*/
private $description;
/**
* Image path
*
* #var string
*
* #ORM\Column(type="text", length=255, nullable=false)
*/
protected $path;
protected function getUploadRootDir()
{
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';
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
* #return Upload
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set description
*
* #param string $description
* #return Upload
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set path
*
* #param string $path
* #return Upload
*/
public function setPath($path)
{
$this->path = $path;
return $this;
}
/**
* Get path
*
* #return string
*/
public function getPath()
{
return $this->path;
}
/**
* Called before saving the entity
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function preUpload()
{
if (null !== $this->file) {
// do whatever you want to generate a unique name
$filename = sha1(uniqid(mt_rand(), true));
$this->path = $filename.'.'.$this->file->guessExtension();
}
}
/**
* Called before entity removal
*
* #ORM\PreRemove()
*/
public function removeUpload()
{
if ($file = $this->getAbsolutePath())
{
unlink($file);
}
}
/**
* Called after entity persistence
*
* #ORM\PostPersist()
* #ORM\PostUpdate()
*/
public function upload()
{
// The file property can be empty if the field is not required
if (null === $this->file) {
return;
}
// Use the original file name here but you should
// sanitize it at least to avoid any security issues
// move takes the target directory and then the
// target filename to move to
$this->file->move(
$this->getUploadRootDir(),
$this->getFile()->getClientOriginalName()
);
// set the path property to the filename where you've saved the file
$this->path = $this->getFile()->getClientOriginalName();
// Clean up the file property as you won't need it anymore
$this->file = null;
}
/**
* Sets file.
*
* #param UploadedFile $file
*#return Upload
*/
public function setFile(File $file = null)
{
$this->file = $file;
}
/**
* Get file.
*
* #return UploadedFile
*/
public function getFile()
{
return $this->file;
}
}
Controller methods
/** This is the homepage for the admin area, for adding,deleting,editing of blog posts.
* #Route("/posted/admin/upload", name="upload")
* #Template()
*/
public function uploadimageAction(Request $request)
{
$upload = new Upload();
//create checkboxtype form
$form = $this->createForm(new ImageFormType(), $upload, array(
'action' => $this->generateUrl('upload'),
'method' => 'POST',
));
$form->handleRequest($request);
if($form->isValid()){
$em = $this->getDoctrine()->getManager();
$upload->upload();
$em->persist($upload);
$em->flush();
// exit(\Doctrine\Common\Util\Debug::dump($post));
return $this->render('BlogBundle:Default:success.html.twig'
);
;
}
return $this->render('BlogBundle:Default:upload.html.twig',array(
'form' =>$form->createView(),
));
}
You are only storing the path in the DB, and only it's necesary that.
Using path you can show the file in your view
pd: you are storing the file in your server with:
$this->file->move(
$this->getUploadRootDir(),
$this->getFile()->getClientOriginalName()
);

Resources