How to correctly delete all images uploaded using sonata-media-bundle

筅森魡賤 提交于 2019-12-11 10:04:44

问题


I have uploaded some images using the sonata-media-bundle, as suggested here

$media = new Media;
$media->setBinaryContent($file->getRealPath());
$media->setContext('myContext'); 
$media->setProviderName('sonata.media.provider.image');
$mediaManager->save($media);

Previous code creates the media correctly all files (according to context config) and db registry. Now what I did to delete the media is calling like this:

$media = $mediaManager->findOneBy(array('id' => $id));
$mediaManager->delete($media)

It correctly deletes the media data from database but not from the configured fileSystem, there are still some images associated to the uploaded media. I'm planning using the S3 filesystem so I need to delete all with the same framework

the most relevant of my sonata configuration (using the suggested too) is like this:

sonata_media: default_context: default db_driver: doctrine_orm class: media: MyApp\MediaBundle\Entity\Media gallery: MyApp\MediaBundle\Entity\Gallery gallery_has_media: MyApp\MediaBundle\Entity\GalleryHasMedia contexts: default: providers: - sonata.media.provider.youtube - sonata.media.provider.image - sonata.media.provider.file formats: small: { width: 200, quality: 77} myContext: providers: - sonata.media.provider.image formats: normal: { width: 350, quality: 75} tmb: { width: 100, quality: 75} filesystem: local: directory: %kernel.root_dir%/../web/uploads/media create: false

Thanks in advance.


回答1:


To be able to correctly delete all media related to the uploaded file, one has to use the appropiate provider:

from the sonata media documentation

A provider class is responsible for handling common things related to a media asset:

  • thumbnails
  • path
  • editing the media with a form
  • storing the media information (metadata)

So the code would look like:

$media = $mediaManager->findOneBy(array('id' => $id));
//assuming you have access through $this->get to the service container
$provider = $this->get($media->getProviderName());
$provider->removeThumbnails($media);
$mediaManager->delete($media)


来源:https://stackoverflow.com/questions/25942476/how-to-correctly-delete-all-images-uploaded-using-sonata-media-bundle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!