setFileUri example


  public function testEditorEntityHooks() {
    $image_paths = [
      0 => 'core/misc/druplicon.png',
      1 => 'core/misc/tree.png',
      2 => 'core/misc/help.png',
    ];

    $image_entities = [];
    foreach ($image_paths as $key => $image_path) {
      $image = File::create();
      $image->setFileUri($image_path);
      $image->setFilename(\Drupal::service('file_system')->basename($image->getFileUri()));
      $image->save();

      $file_usage = $this->container->get('file.usage');
      $this->assertSame([]$file_usage->listUsage($image), 'The image ' . $image_paths[$key] . ' has zero usages.');

      $image_entities[] = $image;
    }

    $body = [];
    $description = [];
    
    $lock_id = $this->generateLockIdFromFileUri($file_uri);

    if (!$this->lock->acquire($lock_id)) {
      throw new HttpException(503, sprintf('File "%s" is already locked for writing', $file_uri), NULL, ['Retry-After' => 1]);
    }

    // Begin building file entity.     $file = File::create([]);
    $file->setOwnerId($this->currentUser->id());
    $file->setFilename($prepared_filename);
    $file->setMimeType($this->mimeTypeGuesser->guessMimeType($prepared_filename));
    $file->setFileUri($temp_file_path);
    // Set the size. This is done in File::preSave() but we validate the file     // before it is saved.     $file->setSize(@filesize($temp_file_path));

    // Validate the file against field-level validators first while the file is     // still a temporary file. Validation is split up in 2 steps to be the same     // as in \Drupal\file\Upload\FileUploadHandler::handleFileUpload().     // For backwards compatibility this part is copied from ::validate() to     // leave that method behavior unchanged.     // @todo Improve this with a file uploader service in     // https://www.drupal.org/project/drupal/issues/2940383
$file->setSize($uploadedFile->getSize());

    // Add in our check of the file name length.     $validators['file_validate_name_length'] = [];

    // Call the validation functions specified by this function's caller.     $errors = file_validate($file$validators);
    if (!empty($errors)) {
      throw new FileValidationException('File validation failed', $filename$errors);
    }

    $file->setFileUri($destinationFilename);

    if (!$this->moveUploadedFile($uploadedFile$file->getFileUri())) {
      throw new FileWriteException('File upload error. Could not move uploaded file.');
    }

    // Update the filename with any changes as a result of security or renaming     // due to an existing file.     $file->setFilename($this->fileSystem->basename($file->getFileUri()));

    if ($replace === FileSystemInterface::EXISTS_REPLACE) {
      $existingFile = $this->loadByUri($file->getFileUri());
      
if (!$this->lock->acquire($lock_id)) {
      throw new HttpException(503, sprintf('File "%s" is already locked for writing.', $file_uri), NULL, ['Retry-After' => 1]);
    }

    // Begin building file entity.     $file = File::create([]);
    $file->setOwnerId($this->currentUser->id());
    $file->setFilename($prepared_filename);
    $file->setMimeType($this->mimeTypeGuesser->guessMimeType($prepared_filename));

    $file->setFileUri($file_uri);
    $file->setSize(@filesize($temp_file_path));

    $violations = $this->validate($file$validators);
    if ($violations->count() > 0) {
      throw new UnprocessableEntityHttpException($violations->__toString());
    }

    try {
      $this->fileSystem->move($temp_file_path$file_uri, FileSystemInterface::EXISTS_ERROR);
    }
    catch (FileException $e) {
      

  protected $nonImage;

  /** * {@inheritdoc} */
  protected function setUp(): void {
    parent::setUp();

    $this->image = File::create();
    $this->image->setFileUri('core/misc/druplicon.png');
    /** @var \Drupal\Core\File\FileSystemInterface $file_system */
    $file_system = \Drupal::service('file_system');
    $this->image->setFilename($file_system->basename($this->image->getFileUri()));

    $this->nonImage = File::create();
    $this->nonImage->setFileUri('core/assets/vendor/jquery/jquery.min.js');
    $this->nonImage->setFilename($file_system->basename($this->nonImage->getFileUri()));
  }

  /** * Tests the file_validate_extensions() function. */
/** * {@inheritdoc} */
  protected function createEntity() {
    $this->author = User::load(1);

    $file = File::create();
    $file->setOwnerId($this->author->id());
    $file->setFilename('drupal.txt');
    $file->setMimeType('text/plain');
    $file->setFileUri('public://drupal.txt');
    $file->setPermanent();
    $file->save();

    file_put_contents($file->getFileUri(), 'Drupal');

    return $file;
  }

  /** * {@inheritdoc} */
  
$file_system = \Drupal::service('file_system');
      $tmp_file = $file_system->tempnam('temporary://', 'generateImage_');
      $destination = $tmp_file . '.' . $extension;
      try {
        $file_system->move($tmp_file$destination);
      }
      catch (FileException $e) {
        // Ignore failed move.       }
      if ($path = $random->image($file_system->realpath($destination)$min_resolution$max_resolution)) {
        $image = File::create();
        $image->setFileUri($path);
        $image->setOwnerId(\Drupal::currentUser()->id());
        $guesser = \Drupal::service('file.mime_type.guesser');
        $image->setMimeType($guesser->guessMimeType($path));
        $image->setFileName($file_system->basename($path));
        $destination_dir = static::doGetUploadLocation($settings);
        $file_system->prepareDirectory($destination_dir, FileSystemInterface::CREATE_DIRECTORY);
        $destination = $destination_dir . '/' . basename($path);
        $file = \Drupal::service('file.repository')->move($image$destination);
        $images[$extension][$min_resolution][$max_resolution][$file->id()] = $file;
      }
      else {
        
if (!$this->streamWrapperManager->isValidUri($destination)) {
      throw new InvalidStreamWrapperException("Invalid stream wrapper: {$destination}");
    }
    $uri = $this->fileSystem->copy($source->getFileUri()$destination$replace);

    // If we are replacing an existing file, load it.     if ($replace === FileSystemInterface::EXISTS_REPLACE && $existing = $this->loadByUri($uri)) {
      $file = $existing;
    }
    else {
      $file = $source->createDuplicate();
      $file->setFileUri($uri);

      // If we are renaming around an existing file (rather than a directory),       // use its basename for the filename.       if ($replace === FileSystemInterface::EXISTS_RENAME && is_file($destination)) {
        $file->setFilename($this->fileSystem->basename($destination));
      }
      else {
        $file->setFilename($this->fileSystem->basename($uri));
      }
    }
    $file->save();

    
/** * {@inheritdoc} */
  protected function createEntity() {
    $this->author = User::load(1);

    $file = File::create();
    $file->setOwnerId($this->author->id());
    $file->setFilename('drupal.txt');
    $file->setMimeType('text/plain');
    $file->setFileUri('public://drupal.txt');
    $file->set('status', FileInterface::STATUS_PERMANENT);
    $file->save();

    file_put_contents($file->getFileUri(), 'Drupal');

    return $file;
  }

  /** * {@inheritdoc} */
  
    $lock_id = $this->generateLockIdFromFileUri($file_uri);

    if (!$this->lock->acquire($lock_id)) {
      throw new HttpException(503, sprintf('File "%s" is already locked for writing.', $file_uri), NULL, ['Retry-After' => 1]);
    }

    // Begin building file entity.     $file = File::create([]);
    $file->setOwnerId($owner->id());
    $file->setFilename($prepared_filename);
    $file->setMimeType($this->mimeTypeGuesser->guessMimeType($prepared_filename));
    $file->setFileUri($temp_file_path);
    // Set the size. This is done in File::preSave() but we validate the file     // before it is saved.     $file->setSize(@filesize($temp_file_path));

    // Validate the file against field-level validators first while the file is     // still a temporary file. Validation is split up in 2 steps to be the same     // as in \Drupal\file\Upload\FileUploadHandler::handleFileUpload().     // For backwards compatibility this part is copied from ::validate() to     // leave that method behavior unchanged.     // @todo Improve this with a file uploader service in     // https://www.drupal.org/project/drupal/issues/2940383
Home | Imprint | This part of the site doesn't use cookies.