Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a file uri to relative path in drupal8

Tags:

php

drupal-8

I'm trying to find the way to convert an uri like

public://field/image/link-carousel.png

to a relative path

sites/default/files/directory/link-carousel.png

(of course this is an example because public:// could have other path).

How to do it?

Code:

 if(isset($article_node['field_image']['und']['n0'])){  
      $uri = $article_node['field_image']['und']['n0']['uri'];
      $realpath = \Drupal::service('file_system')->realpath($uri);
      $path = str_replace($_SERVER['DOCUMENT_ROOT'] . '/', '', $realpath);   
}

here on printing $uri will get public://field/image/link-caribbean-carousel-epic-press-release.png.on printing $realpath it gives a blank page.

like image 319
Moby M Avatar asked Dec 14 '22 19:12

Moby M


1 Answers

Taken from https://gist.github.com/illepic/fa451e49c5c43b4a1742333f109dbfcd:

// public://images/blah.jpg
$drupal_file_uri = File::load($fid)->getFileUri();
// /sites/default/files/images/blah.jpg
$image_path = file_url_transform_relative(file_create_url($drupal_file_uri));
like image 143
rpayanm Avatar answered Dec 17 '22 22:12

rpayanm