Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
File Drupal 8-通过路由模块向浏览器发送文件_File_Module_Controller_Routes_Drupal 8 - Fatal编程技术网

File Drupal 8-通过路由模块向浏览器发送文件

File Drupal 8-通过路由模块向浏览器发送文件,file,module,controller,routes,drupal-8,File,Module,Controller,Routes,Drupal 8,我有一个模块,在这个模块中,.routing.yml中应该有一个新的路由,其中包含: path: '/file_exporter/{filename}' defaults: _controller: '\Drupal\file_exporter\Controller\ExportController::file_export' 在ExportController中,发生了一点神奇的事情,根据用户和其他情况创建了一个文件,这很好,我把这个文件放在模块内的一个临时文件夹中 但是我如何用drup

我有一个模块,在这个模块中,.routing.yml中应该有一个新的路由,其中包含:

path: '/file_exporter/{filename}'
defaults:
  _controller: '\Drupal\file_exporter\Controller\ExportController::file_export'
在ExportController中,发生了一点神奇的事情,根据用户和其他情况创建了一个文件,这很好,我把这个文件放在模块内的一个临时文件夹中

但是我如何用drupal将其发送到浏览器

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

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

诀窍在于使用

下面是一个示例函数,用于设置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');
}