10

I have a custom form in Drupal 8, which has a image upload field. I am storing the file ID of that uploaded image. Now I need to generate the URL of that image.

How can I achieve this?

3

2 Answers 2

22

Get the image file src (url)

$fid = 1;//The file ID   
$file = \Drupal\file\Entity\File::load($fid);
$path = $file->getFileUri();

OR

$path = 'public://images/image.jpg';
$url = \Drupal\image\Entity\ImageStyle::load('medium')->buildUrl($file->getFileUri());
1
  • In your second snippet there's an unused variable $path. What is this? Or is it the dump of the $path variable from the first snippet?
    – leymannx
    Dec 28, 2018 at 8:11
1

This way you can get your stored image file using fid in your custom module

$myconfig = \Drupal::config('yourmodule.settings');
$fid = $myconfig->get('image');

foreach ($fid as $key => $value) {
  $fid1 = $value;
}

$file = \Drupal\file\Entity\File::load($fid1);
$path = $file->getFileUri();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.