Drupal 8 在实体保存时,在私有和公共文件夹之间移动文件。

问题描述 投票:0回答:1

我试图隐藏一个未发布的节点上的文件,我使用调度器在未来发布节点,而链接到该节点的文件还不能被公开访问。我使用调度器在未来发布节点,而链接到该节点的文件还不能被公开访问,我把它们移到了私有文件夹中,但当cron运行时,我必须把文件移回原处。

但当cron运行时,我必须将文件移回原处。这里的问题是,文件到了原来的文件夹,但在文件名和uri后面得到一个_0。

/**
 * Implements hook_entity_presave().
 */
function custom_configuration_entity_presave(EntityInterface $entity) {
  // Automatic fill in title field based on first and lastname.
  if($entity->getEntityTypeId() === 'node' && $entity->hasField('field_files')) {
    if($entity->isPublished()) {
      _custom_configuration_move_files($entity, 'public://', TRUE);
    }
    elseif (!$entity->isPublished()) {
      _custom_configuration_move_files($entity, 'private://', FALSE);
    }
  }
}

而我的帮助函数是用来移动文件的

/**
 * Helper function to move a file
 * @param $entity
 *  the entity object
 * @param $target_stream_directory
 *  the stream directory
 * @param $published
 *  True or false if the entity is being published
 * 
 */
function _custom_configuration_move_files($entity, $target_stream_directory, $published) {
  // Get the files.
  $files_values = $entity->field_files->getValue();

  if(!empty($files_values)) {
    // Set the target directory. Either private or public/name_of_folder.
    $target_directory = $target_stream_directory;

    if($published) {
      // Add the field file directory to the target directory.
      $entity_definitions = $entity->getFieldDefinitions();
      $files_folder = $entity_definitions['field_files']->getSettings();
      $target_directory = $target_stream_directory . $files_folder['file_directory'];
    }

    // Loop over all files and move them.
    foreach($files_values as $file_value) {
      $file = \Drupal\file\Entity\File::load($file_value['target_id']);
      $file = file_move($file, $target_directory, 'FILE_EXISTS_REPLACE');
    }
  }
}

但是cron上的调度程序保存文件时,上面有一个_0.我也尝试通过改变文件名来重新保存文件,但是得到的是'未找到',因为系统上的文件是带_0的。所以下面的方法也不行

// Loop over all files and move them.
    foreach($files_values as $file_value) {
      $file = \Drupal\file\Entity\File::load($file_value['target_id']);
      $file_name = $file->getFilename();
      $full_uri = $target_directory . '/' . $file_name;
      $file = file_move($file, $full_uri, 'FILE_EXISTS_REPLACE');
      $file->setFilename($file_name);
      $file->setFileUri($full_uri);
      $file->save();
    }

谁能给我指点一下吗,谢谢。

filenames drupal-8 file-move
1个回答
0
投票

你可以试试这个。

$old_file_uri = $file->getFileUri();
$path_parts = pathinfo($old_file_uri);
$new_file_uri = $target_directory . '/' . $path_parts['basename'];
© www.soinside.com 2019 - 2024. All rights reserved.