在 Drupal 8 中删除内容文件

Deleting Content Files in Drupal 8

我在 Drupal 8 上删除文件时遇到问题。如何删除任何类型的文件,例如在我的情况下是图片文件(jpg、png 等...)。在 Drupal 7 中,您可以在右侧选择删除文件,但 Drupal 8 没有该选项……仅适用于已发布的页面。如果您不再需要文件,是否有机会出于任何原因删除文件,而不需要任何复杂的任务?

P.S: 我是 Drupal 初学者! 谢谢

在 Drupal 8 中不需要该选项,因为有 cron 会自动运行删除未使用的图像。

Drupal 8 管理界面没有本地方法可以从 Drupal 的文件上传器中删除图像。但是,您可以安装 Drupal 8 IMCE 模块,这将使您在登录时可以访问文件系统。这样你就可以删除文件。

这是模块的 link。 https://www.drupal.org/project/imce

您可以从自定义模块中删除图像。这仅在 Drupal 8.9 中测试过。首先让我解释一下图像处理过程,以便您更好地了解此解决方案是否适合您。 fid 存储在您用来引用图像的自定义 table 列中。它是一个名为file_managed 的table 中的主键,用于存储图像信息。图像存储在“web/sites/default/files”文件夹中。这可能会有所不同,具体取决于您的 Drupal 安装。 table_usage 存储图像在网站上的使用情况。当您擦除图像时,您需要从所有三个 tables file_managed、file_usage 和您的 table 中擦除带有图像 fid 的行。然后当然要取消链接你的图片。

    /**
 * Removes an image.
*
* @param $fid
* @return boolean
*/
public function removeImage($fid) {
    if ( empty($fid) || !preg_match('/^[0-9]+$/', trim($fid)) ) return FALSE;

    // Im assigning the $this->database property an instance of Connection
    $result = $this->database->query("SELECT uri FROM {file_managed} where fid=:fid", [':fid' => $fid])->fetchCol();

    $absolute_path = \Drupal::service('file_system')->realpath($result[0]);
    if(isset($absolute_path)) unlink($absolute_path);
    //var_dump($absolute_path); exit();

    $this->database->delete('file_managed')
        ->condition('fid', $fid)
        ->execute(); 
        
    $this->database->delete('file_usage')
        ->condition('fid', $fid)
        ->execute();

    return true;
}