Symfony 4-VichUploader可以删除文件吗?

时间:2019-09-09 10:55:25

标签: file symfony vichuploaderbundle

在我的Symfony 4项目中,当用户上传文件时,我想替换$ user文件属性。

所以我想删除以前的文件,然后用新文件替换。

我发现了这个:https://github.com/dustin10/VichUploaderBundle/blob/ed88af73ab04a5c4908baffad009bc1e47631a01/Storage/AbstractStorage.php#L84

功能:

public function remove($obj, PropertyMapping $mapping)
{
    $name = $mapping->getFileName($obj);
    // the non-strict comparison is done on purpose: we want to skip
    // null and empty filenames
    if (null == $name) {
        return false;
    }
    return $this->doRemove($mapping, $mapping->getUploadDir($obj), $name);
}

但是如何在服务中使用它替换文件?

1 个答案:

答案 0 :(得分:0)

配置Vich提供的生命周期事件:

# config/packages/vich_uploader.yaml or app/config/config.yml
vich_uploader:
    db_driver: orm
    mappings:
        product_image:
            uri_prefix: /images/products
            upload_destination: '%kernel.project_dir%/public/images/products'

            inject_on_load: false
            delete_on_update: true
            delete_on_remove: true

请注意 delete_on_update delete_on_remove 参数。

https://github.com/dustin10/VichUploaderBundle/blob/master/Resources/doc/usage.md#step-3-configure-the-lifecycle-events-optional-step