簡體   English   中英

如何將文件 uri 轉換為 drupal8 中的相對路徑

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

我正在嘗試找到轉換 uri 的方法

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

到相對路徑

站點/默認/文件/目錄/link-carousel.png

(當然這是一個例子,因為 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將獲得 public://field/image/link-caribbean-carousel-epic-press-release.png.on 打印$realpath它給出一個空白頁。

取自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));
/** @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

從 Drupal 9.3 開始,您可以:

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

請參閱: https ://www.drupal.org/node/2940031

使用FileSystem :: realpath()從包裹了sream的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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM