【问题标题】:Drupal 8 - sending files to browser via route moduleDrupal 8 - 通过路由模块将文件发送到浏览器
【发布时间】:2016-03-09 18:10:44
【问题描述】:

我有一个模块,在这个模块内,.routing.yml 中应该有一个新路由:

path: '/file_exporter/{filename}'
defaults:
  _controller: '\Drupal\file_exporter\Controller\ExportController::file_export'

在 ExportController 内部,发生了一些神奇的事情,根据用户和其他情况创建一个文件,这工作正常,我将此文件放在模块内的临时文件夹中。

但是我怎么能用drupal把它发送到浏览器呢?

目标是,我在另一个站点上有指向 /fileexporter/file_123.xyz 的链接,单击此链接可让浏览器直接下载新生成的 file_123.xyz

是否有我可以扩展的类,或者我可以在 Drupal 8 中使用的函数通过路由和控制器将文件直接发送到浏览器?

【问题讨论】:

    标签: file module controller routes drupal-8


    【解决方案1】:

    诀窍在于使用BinaryFileResponse

    这是一个处理设置 HTTP 标头和内容类型并返回 BinaryFileResponse 的示例函数:

    <?php
    // $uri: the file you want to send, as a URI (e.g. private://somefile.txt)
    // $ofilename: the output filename, this will be displayed in the browser.
    // $contenttype: the mime content type for the browser
    // $delete_after_send: delete the file once it's been sent to the browser
    
    function mymodule_transfer_file($uri, $ofilename, $contenttype = NULL, $delete_after_send = FALSE) {
    
      $mime = \Drupal::service('file.mime_type.guesser')->guess($uri);
    
      $headers = array(
        'Content-Type' => $mime . '; name="' . Unicode::mimeHeaderEncode(basename($uri)) . '"',
        'Content-Length' => filesize($uri),
        'Content-Disposition' => 'attachment; filename="' . Unicode::mimeHeaderEncode($ofilename) . '"',
        'Cache-Control' => 'private',
      );
    
      if (isset($contenttype)) {
        $headers['Content-Type'] = $contenttype;
      }
    
      if ($delete_after_send) {
        // Delete after end of script.
        drupal_register_shutdown_function('file_unmanaged_delete', $uri);
      }
    
      $uri_obj = new Uri($uri);
      return new BinaryFileResponse($uri, 200, $headers, $uri_obj->getScheme() !== 'private');
    }
    

    【讨论】:

      猜你喜欢
      • 2012-07-03
      • 1970-01-01
      • 1970-01-01
      • 2019-07-21
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 2016-04-09
      • 1970-01-01
      相关资源
      最近更新 更多