How to resolve a File object from a Vich field
19 June 2026 (Updated 19 June 2026)
Assuming you have a User entity with a photo property that’s a Vich field (i.e., contains the VichUploadable attribute), you can do something like this:
<?php
$this->vichService->resolveFile($user, 'photo');
Where the VichService::resolveFile() method has the following implementation:
<?php
declare(strict_types=1);
namespace App\Service;
use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Storage\StorageInterface;
readonly class VichService
{
public function __construct(private StorageInterface $storage)
{
}
/**
* Resolve a File object from the specified object and mapping name.
*/
public function resolveFile(object $object, string $fieldName): File
{
if (!property_exists($object, $fieldName)) {
throw new \LogicException(sprintf("The object %s has no property '%s'", get_class($object), $fieldName));
}
$stream = $this->storage->resolveStream($object, $fieldName);
$tempFilePath = tempnam(sys_get_temp_dir(), get_class($object) . '_');
file_put_contents($tempFilePath, $stream);
return new File($tempFilePath);
}
}
Tagged:
Symfony recipes