如何 return 来自自定义 wordpress rest api 端点的二进制数据

How to return binary data from custom wordpress rest api endpoint

我正在按照此处的指南在 wordpress 中为 REST api 编写自定义端点:https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/

我可以写一个端点,returns json 数据。但是我如何编写一个 return 二进制数据(pdf、png 和类似文件)的端点?

我的 restpoint 函数 return 是 WP_REST_Response(如果出错则为 WP_Error)。 但是我不知道如果我想用二进制数据响应我应该 return。

我会看一个叫做 DOMPDF 的东西。简而言之,它将任何 HTML DOM 直接流式传输到浏览器。 我们使用它直接从 woo 管理员生成发票的实时副本,根据 $wp_query 结果生成小册子等。浏览器可以呈现的任何内容都可以通过 DOMPDF 流式传输。

聚会迟到了,但我觉得接受的答案并没有真正回答问题,Google 在搜索相同的解决方案时发现了这个问题,所以这就是我最终解决相同问题的方法(即避免使用 WP_REST_Response 并在 WP 尝试发送除我的二进制数据以外的任何其他内容之前终止 PHP 脚本)。

function download(WP_REST_Request $request) {
  $dir = $request->get_param("dir");

  // The following is for security, but my implementation is out 
  // of scope for this answer. You should either skip this line if 
  // you trust your client, or implement it the way you need it.
  $dir = sanitize_path($dir);

  $file = $request->get_param("file");

  // See above...
  $file = sanitize_path($file);

  $sandbox = "/some/path/with/shared/files";
  
  // full path to the file
  $path = $sandbox.$dir.$file;

  $name = basename($path);

  // get the file mime type 
  $finfo = finfo_open(FILEINFO_MIME_TYPE);
  $mime_type = finfo_file($finfo, $path);

  // tell the browser what it's about to receive
  header("Content-Disposition: attachment; filename=$name;");
  header("Content-Type: $mime_type");
  header("Content-Description: File Transfer");
  header("Content-Transfer-Encoding: binary");
  header('Content-Length: ' . filesize($path));
  header("Cache-Control: no-cache private");

  // stream the file without loading it into RAM completely
  $fp = fopen($path, 'rb');
  fpassthru($fp);

  // kill WP
  exit;
}