WP_REST_Response下载文件

Die*_*anò 5 php rest wordpress wordpress-rest-api

是否可以使用WP_REST_ResponseWordPress中的文档返回文档(生成的PDF,CSV)?

到目前为止,我一直在使用注册一个自定义终结点,register_rest_resource但是如果我尝试返回文件(例如,使用PHP fpassthru($f)或readfile($f)收到“已发送标头”)错误。

换句话说:如何使用Wordpress REST API返回文件?

任何帮助表示赞赏!

谢谢

Phi*_*ipp 10

默认情况下,所有 REST 响应都会传递json_encode()以返回 JSON 字符串。但是,REST 服务器提供了 WP 挂钩rest_pre_serve_request,我们可以使用它来返回二进制数据。

\n

代码示例:

\n
<?php\n/**\n * Serves an image via the REST endpoint.\n *\n * By default, every REST response is passed through json_encode(), as the\n * typical REST response contains JSON data.\n *\n * This method hooks into the REST server to return a binary image.\n *\n * @param string $path Absolute path to the image to serve.\n * @param string $type The image mime type [png|jpg|gif]. Default is \'png\'.\n *\n * @return WP_REST_Response The REST response object to serve an image.\n */\nfunction my_serve_image( $path, $type = \'png\' ) {\n    $response = new WP_REST_Response;\n\n    if ( file_exists( $path ) ) {\n        // Image exists, prepare a binary-data response.\n        $response->set_data( file_get_contents( $path ) );\n        $response->set_headers( [\n            \'Content-Type\'   => "image/$type",\n            \'Content-Length\' => filesize( $path ),\n        ] );\n\n        // HERE \xe2\x86\x92 This filter will return our binary image!\n        add_filter( \'rest_pre_serve_request\', \'my_do_serve_image\', 0, 2 );\n    } else {\n        // Return a simple "not-found" JSON response.\n        $response->set_data( \'not-found\' );\n        $response->set_status( 404 );\n    }\n\n    return $response;\n}\n\n/**\n * Action handler that is used by `serve_image()` to serve a binary image\n * instead of a JSON string.\n *\n * @return bool Returns true, if the image was served; this will skip the\n *              default REST response logic.\n */\nfunction my_do_serve_image( $served, $result ) {\n    $is_image   = false;\n    $image_data = null;\n\n    // Check the "Content-Type" header to confirm that we really want to return\n    // binary image data.\n    foreach ( $result->get_headers() as $header => $value ) {\n        if ( \'content-type\' === strtolower( $header ) ) {\n            $is_image   = 0 === strpos( $value, \'image/\' );\n            $image_data = $result->get_data();\n            break;\n        }\n    }\n\n    // Output the binary data and tell the REST server to not send any other\n    // details (via "return true").\n    if ( $is_image && is_string( $image_data ) ) {\n        echo $image_data;\n\n        return true;\n    }\n\n    return $served;\n}\n
Run Code Online (Sandbox Code Playgroud)\n

使用示例:

\n
<?php\n// Register the REST endpoint.\nregister_rest_route( \'my_sample/v1\', \'image\', [\n    \'method\' => \'GET\',\n    \'callback\' => \'my_rest_get_image\'\n] );\n\n// Return the image data using our function above.\nfunction my_rest_get_image() {\n    return my_serve_image( \'path/to/image.jpeg\', \'jpg\' );\n}\n
Run Code Online (Sandbox Code Playgroud)\n


Cle*_*oom 0

(我自己很快就需要这个,所以制定一个可能不完整的答案)

通过与 WP Media 核实,我们得到了包含所需媒体文件链接的响应.../?rest_route=/wp/v2/media/ID。JSON API

接下来即为其中source _url包含的图像之一.../wp-content/uploads/2021/06/Screenshot-2021-06-18-at-10.25.05-150x150.png。

在注释之后(不流式传输二进制文件,而是链接),将文件添加到 WP Media 集合,或者自定义端点可以使用链接到生成的和存储的文件的类似响应进行响应。

然后任何 JSON API 兼容的客户端都可以执行所需的操作。在这种情况下生成下载链接。