php 如何在drupal8中将文件uri转换为相对路径

s4n0splo  于 2022-12-25  发布在  PHP
关注(0)|答案(4)|浏览(123)

我正在尝试找到转换URI的方法
public://field/image/link-carousel.png
到相对路径
sites/default/files/directory/link-carousel.png
(of当然,这只是一个示例,因为public://可能有其他路径)。
怎么做呢?
代码:

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);   
}

在这里打印$uri将得到公开://field/image/link-caribbean-carousel-epic-press-release.png。在打印$realpath时,它给出了一个空白页。

idv4meu8

idv4meu81#

取自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));
0wi1tuuw

0wi1tuuw2#

/** @var Drupal\file\Entity\File $file */
$file = // get file.
$file->createFileUrl(TRUE); // to get relative path
$file->createFileUrl(FALSE); // to get absolute path https://

链接:https://api.drupal.org/api/drupal/core%21modules%21file%21src%21Entity%21File.php/function/File%3A%3AcreateFileUrl/8.7.x

xytpbqjk

xytpbqjk3#

使用FileSystem::realpath()从sream Package 的URI进行转换:

use Drupal\Core\File\FileSystem;

//$realpath = drupal_realpath($uri); // D7, D8 deprecated
$realpath = FileSystem::realpath($uri);
$path = str_replace($_SERVER['DOCUMENT_ROOT'].'/','',$realpath);

UPD:由于某些原因,上面的例子是无效的,我们需要使用file_system服务代替:

$uri = $node->field_document->entity->getFileUri();
  $realpath = \Drupal::service('file_system')->realpath($uri);
  $path = str_replace($_SERVER['DOCUMENT_ROOT'] . '/', '', $realpath);
8nuwlpux

8nuwlpux4#

从Drupal 9.3开始,您可以:

$relativePathToFile = \Drupal::service('file_url_generator')->generateString($thumbnailUri);

参见:https://www.drupal.org/node/2940031

相关问题