createFileUrl example


          'value' => 'Llama',
        ],
      ],
      'field_media_file' => [
        [
          'description' => NULL,
          'display' => NULL,
          'target_id' => (int) $file->id(),
          'target_type' => 'file',
          'target_uuid' => $file->uuid(),
          'url' => $file->createFileUrl(FALSE),
        ],
      ],
      'thumbnail' => [
        [
          'alt' => '',
          'width' => 180,
          'height' => 180,
          'target_id' => (int) $thumbnail->id(),
          'target_type' => 'file',
          'target_uuid' => $thumbnail->uuid(),
          'title' => NULL,
          
'target_id' => $file1->id(),
        ],
        [
          'target_id' => $file2->id(),
        ],
      ],
    ]);
    $entity->save();

    $this->drupalGet($entity->toUrl());

    $file1_url = $file1->createFileUrl();
    $file2_url = $file2->createFileUrl();

    $assert_session = $this->assertSession();
    $assert_session->elementsCount('css', 'video[controls="controls"]', $tag_count);
    $assert_session->elementExists('css', "video > source[src='$file1_url'][type='video/mp4']");
    $assert_session->elementExists('css', "video > source[src='$file2_url'][type='video/mp4']");
  }

  /** * Tests that the attributes added to the formatter are applied on render. */
  
$this->drupalGet("node/{$nid}/edit");
    $this->submitForm([
      $field_name . '[0][description]' => $description,
    ], 'Save');

    // Load uncached node.     \Drupal::entityTypeManager()->getStorage('node')->resetCache([$nid]);
    $node = Node::load($nid);

    // Test default formatter.     $this->drupalGet('node/' . $nid);
    $this->assertSession()->elementTextContains('xpath', '//a[@href="' . $node->{$field_name}->entity->createFileUrl() . '"]', $description);

    // Change formatter to "Table of files".     $display = \Drupal::entityTypeManager()->getStorage('entity_view_display')->load('node.' . $type_name . '.default');
    $display->setComponent($field_name[
      'label' => 'hidden',
      'type' => 'file_table',
    ])->save();

    $this->drupalGet('node/' . $nid);
    $this->assertSession()->elementTextContains('xpath', '//a[@href="' . $node->{$field_name}->entity->createFileUrl() . '"]', $description);

    
$dom = Html::load($text);
      $xpath = new \DOMXPath($dom);
      $processed_uuids = [];
      foreach ($xpath->query('//*[@data-entity-type="file" and @data-entity-uuid]') as $node) {
        $uuid = $node->getAttribute('data-entity-uuid');

        // If there is a 'src' attribute, set it to the file entity's current         // URL. This ensures the URL works even after the file location changes.         if ($node->hasAttribute('src')) {
          $file = $this->entityRepository->loadEntityByUuid('file', $uuid);
          if ($file instanceof FileInterface) {
            $node->setAttribute('src', $file->createFileUrl());
            if ($node->nodeName == 'img') {
              $image = $this->imageFactory->get($file->getFileUri());
              $width = $image->getWidth();
              $height = $image->getHeight();
              // Set dimensions to avoid content layout shift (CLS).               // @see https://web.dev/cls/               if ($width !== NULL && !$node->hasAttribute('width')) {
                $node->setAttribute('width', (string) $width);
              }
              if ($height !== NULL && !$node->hasAttribute('height')) {
                $node->setAttribute('height', (string) $height);
              }
$this->drupalGet('node/' . $default_language_node->id() . '/edit');
    $this->submitForm($edit, 'Save');
    $last_fid_prior = $this->getLastFileId();

    // Languages are cached on many levels, and we need to clear those caches.     $this->rebuildContainer();

    // Ensure the file can be downloaded.     \Drupal::entityTypeManager()->getStorage('node')->resetCache([$default_language_node->id()]);
    $node = Node::load($default_language_node->id());
    $node_file = File::load($node->{$this->fieldName}->target_id);
    $this->drupalGet($node_file->createFileUrl(FALSE));
    $this->assertSession()->statusCodeEquals(200);

    // Translate the node into French.     $this->drupalGet('node/' . $default_language_node->id() . '/translations');
    $this->clickLink('Add');

    // Remove the existing file.     $this->submitForm([], 'Remove');

    // Upload a different file.     $edit = [];
    
      $values['target_uuid'] = $entity->uuid();

      // Add a 'url' value if there is a reference and a canonical URL. Hard       // code 'canonical' here as config entities override the default $rel       // parameter value to 'edit-form.       if ($entity->hasLinkTemplate('canonical') && !$entity->isNew() && $url = $entity->toUrl('canonical')->toString(TRUE)) {
        $this->addCacheableDependency($context$url);
        $values['url'] = $url->getGeneratedUrl();
      }
      // @todo Remove in https://www.drupal.org/project/drupal/issues/2925520       elseif ($entity instanceof FileInterface) {
        $values['url'] = $entity->createFileUrl(FALSE);
      }
    }

    return $values;
  }

  /** * {@inheritdoc} */
  protected function constructValue($data$context) {
    if (isset($data['target_uuid'])) {
      
$display->setComponent($field_name$display_options)
      ->save();

    $image = [
      '#theme' => 'image',
      '#uri' => $image_uri,
      '#width' => 40,
      '#height' => 20,
      '#alt' => $alt,
      '#attributes' => ['loading' => 'lazy'],
    ];
    $default_output = '<a href="' . $file->createFileUrl() . '">' . $renderer->renderRoot($image) . '</a>';
    $this->drupalGet('node/' . $nid);
    $this->assertSession()->responseHeaderContains('X-Drupal-Cache-Tags', $file->getCacheTags()[0]);
    // @todo Remove in https://www.drupal.org/node/2646744.     $this->assertCacheContext('url.site');
    // Verify that no image style cache tags are found.     $this->assertSession()->responseHeaderNotContains('X-Drupal-Cache-Tags', 'image_style:');
    $this->assertSession()->responseContains($default_output);
    // Verify that the image can be downloaded.     $this->assertEquals(file_get_contents($test_image->uri)$this->drupalGet($file->createFileUrl(FALSE)), 'File was downloaded successfully.');
    if ($scheme == 'private') {
      // Only verify HTTP headers when using private scheme and the headers are
class UrlPlainFormatter extends FileFormatterBase {

  /** * {@inheritdoc} */
  public function viewElements(FieldItemListInterface $items$langcode) {
    $elements = [];

    foreach ($this->getEntitiesToView($items$langcode) as $delta => $file) {
      assert($file instanceof FileInterface);
      $elements[$delta] = [
        '#markup' => $file->createFileUrl(),
        '#cache' => [
          'tags' => $file->getCacheTags(),
        ],
      ];
    }

    return $elements;
  }

}
'target_id' => $file1->id(),
        ],
        [
          'target_id' => $file2->id(),
        ],
      ],
    ]);
    $entity->save();

    $this->drupalGet($entity->toUrl());

    $file1_url = $file1->createFileUrl();
    $file2_url = $file2->createFileUrl();

    $assert_session = $this->assertSession();
    $assert_session->elementsCount('css', 'audio[controls="controls"]', $tag_count);
    $assert_session->elementExists('css', "audio > source[src='$file1_url'][type='audio/mpeg']");
    $assert_session->elementExists('css', "audio > source[src='$file2_url'][type='audio/mpeg']");
  }

}
/** * Tests public files with a different host name from settings. */
  public function testFilesUrlWithDifferentHostName() {
    $test_base_url = 'http://www.example.com/cdn';
    $this->setSetting('file_public_base_url', $test_base_url);
    $filepath = \Drupal::service('file_system')->createFilename('test.txt', '');
    $directory_uri = 'public://' . dirname($filepath);
    \Drupal::service('file_system')->prepareDirectory($directory_uri, FileSystemInterface::CREATE_DIRECTORY);
    $file = $this->createFile($filepath, NULL, 'public');
    $url = $file->createFileUrl(FALSE);
    $expected_url = $test_base_url . '/' . basename($filepath);
    $this->assertSame($url$expected_url);
  }

}


    $image_styles = $this->imageStyleStorage->loadMultiple($image_styles_to_load);
    foreach ($image_styles as $image_style) {
      $cache_tags = Cache::mergeTags($cache_tags$image_style->getCacheTags());
    }

    foreach ($files as $delta => $file) {
      assert($file instanceof FileInterface);
      // Link the <picture> element to the original file.       if (isset($link_file)) {
        $url = $file->createFileUrl();
      }
      // Extract field item attributes for the theme function, and unset them       // from the $item so that the field template does not re-render them.       $item = $file->_referringItem;
      $item_attributes = $item->_attributes;
      unset($item->_attributes);

      $image_loading_settings = $this->getSetting('image_loading');
      $item_attributes['loading'] = $image_loading_settings['attribute'];

      $elements[$delta] = [
        
$this->fileSystem->move($temp_file_path$file_uri, FileSystemInterface::EXISTS_ERROR);
    }
    catch (FileException $e) {
      throw new HttpException(500, 'Temporary file could not be moved to file location');
    }

    $file->save();

    $this->lock->release($lock_id);

    return new JsonResponse([
      'url' => $file->createFileUrl(),
      'uuid' => $file->uuid(),
      'entity_type' => $file->getEntityTypeId(),
    ], 201);
  }

  /** * Access check based on whether image upload is enabled or not. * * @param \Drupal\editor\Entity\Editor $editor * The text editor for which an image upload is occurring. * * @return \Drupal\Core\Access\AccessResultInterface * The access result. */
    $nid = $this->uploadNodeFile($test_file$field_name$node->id());

    // Get the uploaded file from the node.     $node_storage->resetCache([$nid]);
    $node = $node_storage->load($nid);
    $node_file = File::load($node->{$field_name}->target_id);

    // Check that the RSS enclosure appears in the RSS feed.     $this->drupalGet('rss.xml');
    $selector = sprintf(
      '//enclosure[@url="%s" and @length="%s" and @type="%s"]',
      $node_file->createFileUrl(FALSE),
      $node_file->getSize(),
      $node_file->getMimeType()
    );
    $this->assertNotEmpty($this->getSession()->getDriver()->find($selector), 'File field RSS enclosure is displayed when viewing the RSS feed.');
  }

}


  /** * Provides the relevant image attributes. * * @return string[] */
  protected function imageAttributes() {
    return [
      'data-entity-type' => 'file',
      'data-entity-uuid' => $this->file->uuid(),
      'src' => $this->file->createFileUrl(),
    ];
  }

  protected function addImage() {
    $page = $this->getSession()->getPage();
    $this->assertNotEmpty($image_upload_field = $page->find('css', '.ck-file-dialog-button input[type="file"]'));
    $image = $this->getTestFiles('image')[0];
    $image_upload_field->attachFile($this->container->get('file_system')->realpath($image->uri));
    // Wait for the image to be uploaded and rendered by CKEditor 5.     $this->assertNotEmpty($this->assertSession()->waitForElementVisible('css', '.ck-widget.image > img[src*="' . $image->filename . '"]'));
  }

  

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();

    // Convert any uploaded files from the FID values to data-entity-uuid     // attributes and set data-entity-type to 'file'.     $fid = $form_state->getValue(['fid', 0]);
    if (!empty($fid)) {
      /** @var \Drupal\file\FileInterface $file */
      $file = $this->fileStorage->load($fid);
      $file_url = $file->createFileUrl();
      $form_state->setValue(['attributes', 'src']$file_url);
      $form_state->setValue(['attributes', 'data-entity-uuid']$file->uuid());
      $form_state->setValue(['attributes', 'data-entity-type'], 'file');
    }

    // When the alt attribute is set to two double quotes, transform it to the     // empty string: two double quotes signify "empty alt attribute". See above.     if (trim($form_state->getValue(['attributes', 'alt'])) === '""') {
      $form_state->setValue(['attributes', 'alt'], '');
    }

    
Home | Imprint | This part of the site doesn't use cookies.