You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Symfony自定义上传图片文件名:VichUpload无法满足特殊命名规则需求

Got it, let's break down how to solve your VichUploader customization needs, starting with the clear School logo upload scenario first, then cover a flexible approach for your second entity once you lock in its requirements.

Solution for School Entity Logo Upload

VichUploader's default namers don't cover this exact path/naming rule, but we can build custom namers to handle it perfectly. Here's how:

1. Create a Custom Directory Namer

This will handle the ../web/files/schools/[school_id]/logo/ path structure. We'll format the school ID to 6 digits (like 000001) as shown in your example.

Create the class src/Uploader/Namer/SchoolLogoDirectoryNamer.php:

<?php

namespace App\Uploader\Namer;

use Vich\UploaderBundle\Naming\DirectoryNamerInterface;
use Vich\UploaderBundle\Mapping\PropertyMapping;
use App\Entity\School;

class SchoolLogoDirectoryNamer implements DirectoryNamerInterface
{
    public function getDirectoryName($object, PropertyMapping $mapping): string
    {
        if (!$object instanceof School) {
            throw new \InvalidArgumentException('This namer only works with School entities!');
        }

        // Format school ID to 6 leading zeros
        $formattedId = sprintf('%06d', $object->getId());

        // Return relative path from web root (Vich will handle the base path)
        return sprintf('schools/%s/logo', $formattedId);
    }
}

2. Create a Custom File Namer (for fixed "logo.png" filename)

Since your example uses logo.png instead of a dynamic filename, we'll force the filename to be logo (Vich will append the correct extension from the uploaded file, or you can hardcode it if needed).

Create src/Uploader/Namer/SchoolLogoFileNamer.php:

<?php

namespace App\Uploader\Namer;

use Vich\UploaderBundle\Naming\FileNamerInterface;
use Vich\UploaderBundle\Mapping\PropertyMapping;
use App\Entity\School;

class SchoolLogoFileNamer implements FileNamerInterface
{
    public function getName($object, PropertyMapping $mapping): string
    {
        if (!$object instanceof School) {
            throw new \InvalidArgumentException('This namer only works with School entities!');
        }

        // Return fixed filename (without extension; Vich adds it automatically)
        return 'logo';
    }
}

3. Configure VichUploader to Use These Namers

Update your config/packages/vich_uploader.yaml to map these custom namers to the School entity's upload field:

vich_uploader:
    db_driver: orm
    mappings:
        school_logo:
            uri_prefix: /files/schools
            upload_destination: '%kernel.project_dir%/../web/files'
            directory_namer: App\Uploader\Namer\SchoolLogoDirectoryNamer
            file_namer: App\Uploader\Namer\SchoolLogoFileNamer
            # Optional: overwrite existing logos when updating
            delete_on_update: true
            delete_on_remove: true

Don't forget to link this school_logo mapping to the upload field in your School entity using VichUploader annotations or config.


Handling the Second Entity (Flexible Approach)

Since your second entity's requirements aren't fully defined, here are two scalable patterns to adapt once you have the details:

  • Separate Custom Namers: Repeat the above pattern—create unique directory/file namers for the second entity, then add a new mapping in vich_uploader.yaml pointing to those classes. This keeps each entity's upload logic clean and isolated.
  • Single Namer with Entity Checks: If the second entity has similar but adjusted rules, build a single namer class that checks which entity it's handling and adapts the path/filename accordingly. For example:
    public function getDirectoryName($object, PropertyMapping $mapping): string
    {
        if ($object instanceof School) {
            // School path logic here
        } elseif ($object instanceof SecondEntity) {
            // Second entity path logic here
        } else {
            throw new \InvalidArgumentException('Unsupported entity type!');
        }
    }
    

Either way, VichUploader's extensible namer system lets you tailor storage and naming to any scenario.


内容的提问来源于stack exchange,提问作者Oscar Manuel Gómez Senovilla

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:21:12