How can a Url
object be created from a file URI? Using the URI for a public file as a parameter for Url::fromUri()
gives this error.
UnexpectedValueException: External URLs do not have internal route parameters. in Drupal\Core\Url->getRouteParameters().
$file = File::load($file_id);
$file_uri = $file->getFileUri();
$menu_link['url'] = Url::fromUri($file_uri);
Here is the class and method in question: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Url.php/function/Url%3A%3AfromUri/8.2.x
Note that I don't need to get the actual URL in string format, I need to generate a Url object from the Url class that points to a file. This is because I am attempting to modify the path of a menu link and unfortunately that is not a simple matter of providing a URL string in Drupal 8.
This is the code I am using.
function teeprop_preprocess_menu__main(&$vars) {
foreach($vars['items'] as $key => $menu_link) {
if (!empty($menu_link['url']->getRouteParameters())) {
$node_id = $menu_link['url']->getRouteParameters()['node'];
$node_entity = Node::load($node_id);
$node_type = $node_entity->getType();
if ($node_type == 'pdf') {
$file_id = $node_entity->get('field_pdf_file')->getValue()[0]['target_id'];
$file = File::load($file_id);
// $file_url = $file->url();
$file_uri = $file->getFileUri();
$vars['items'][$key]['url'] = Url::fromUri($file_uri, ['absolute' => TRUE]);
}
}
}
}
$menu_link['url'] = Url::fromUri($file_uri, ['absolute' => TRUE]);
. I'm not confident in this, but I use this in freelinking module to send file URIs to Link render element's #uri property.