How to create a URL to an unmanaged public file in Drupal 8 I'm running into a problem creating a URL to an unmanaged file in the "public" file directory (this is for the file_example for Drupal 8).

The following code will throw an exception:

use Drupal\Core\Url;

$stuff = "content for an unmanaged file\n";
$dest = file_unmanaged_save_data($data, "public://unmanaged-mahem.txt");

print "URI: $dest\n";
$url = Url::fromUri($dest);
$our_uri = $url-&gt;getUri();
print "Our URL was created, and thinks it corresponds to the URI $our_uri\n";

//but this throws:
$external_link = \Drupal::l(t('External link'), $url);
print "External Link: $external_link\n";


When run, here's what you see (the stack trace is removed):

$ drush @d8 scr unmanaged-mahem.php
URI: public://unmanaged-mahem_1.txt
Our URL was created, and thinks it corresponds to the URI public://unmanaged-mahem.txt
exception 'InvalidArgumentException' with message 'The URI 'public://unmanaged-mahem_1.txt' is invalid. You must use a valid URI scheme. Use base: for a path, e.g., to a Drupal file that needs the base path. Do not use this for internal
paths controlled by Drupal.' in /var/www/drupal/core/lib/Drupal/Core/Utility/UnroutedUrlAssembler.php:69


I'm not sure if this is a bug or if this is by design, since in general, you'd want to use a managed file for anything in the public files directory that was for public consumption.  But the change record doesn't say anything about this.

Is there a valid way to create a link to an unmanaged file in Drupal 8?
You need to run the file path through file_create_url() and then use it together with base:

Url::fromUri(file_create_url($dest));


(file_create_url() should return absolute URL's, so you don't need base)

There's an issue to simplify that: https://www.drupal.org/node/2539622