3

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->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?

7

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

  • @Bendir -- this mostly works, thanks. I'm having trouble tracing down some corner cases in SimpleTest where the resulting links still blow up (Url::toString() seems particularly dangerous). If you folks can get the fix in for the Core issue, much obliged, because for now, the URL link generator is a loaded grenade :-( – Torenware Networks Oct 19 '15 at 0:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.