Closed winds1983 closed 7 years ago
Use an event listener and subsbscribe to the event `PostUpload'.
You get the metadata like destination directory from $event->getMapping()
and the file from $event->getObject()
.
@Dragnucs Ok, Thanks.
I've created the event listener (Please update events documentation if you can) but it's not getting called...
admin.event.vich_uploader_post_upload:
class: Administration\SystemBundle\EventListener\VichImageHandling
tags:
- { name: kernel.event_listener, event: vich_uploader.post_upload , method: resizeImage }
namespace Administration\SystemBundle\EventListener;
use Symfony\Component\HttpKernel\HttpKernel;
use Vich\UploaderBundle\Event\Event;
class VichImageHandling
{
public function resizeImage(Event $event)
{
$uploadedFile = $event->getObject();
dump($uploadedFile);
return null;
}
}
is there anything I'm missing?
And also I'm using sonata admin bundle.
@AienTech I did what you wrote but dump is not displayed :/
@z0om this is a pretty old issue, which unfortunately I can't remember what I did to fix it. back then I was using Symfony 2.7. I believe since then the API has been changed. Not sure thou
@AienTech It is ok, it works. Just add "exit" after the dump to see dump results.
@AienTech It is ok, it works. Just add "exit" after the dump to see dump results.
@z0om I'm not sure if exit
is the right solution. This is out of the context, but have you checked your Debug Console? it should actually appear there whenever you use dump()
.
@AienTech It works fine for dumping but I have a bigger problem : I don't want to resize images for all entities. How can I do that ?
I guess that once you get your object, you can retrieve related entity (and then decide what to do)
@garak I get my fields of the object but how can I know which entity it is ?
[...]
class VichImageHandling
{
public function resizeImage(Event $event)
{
$uploadedFile = $event->getObject();
dump($uploadedFile);
[...]
Here the result of dump :
It's App\Entity\Pronostic
yes, I can see it with the dump but how to have it with PHP ?
Well, it's inside the same variable you dumped above...
@z0om I think what you're looking for is the instanceof operator.
I would have written a switch statement in this situation and checked which instance my class is, and do the stuff accordingly...
After receiving uploaded file using $event->getMapping(); Get that file this way:
$mapping = $event->getMapping();
$propertyName = $mapping->getFilePropertyName();
$object = $event->getObject();
$getter = 'get'.ucfirst($propertyName);
$file = $object->$getter();
Then use Intervention image for resize:
$image = Image::make($file->getPathname());
$image->resize(400, 300); // Adjust the dimensions as needed
$image->save($file->getPathname());
$file->setOriginalSize($image->filesize());
$file->setMimeType($image->mime());
Now I use VichUploaderBundle + KnpGaufretteBundle to upload image to AWS s3, but how to resize image size when upload?