webman如何通过url获取文件流直接转发给客户端?

RainLee1990

问题描述

根据url直接获取文件流发送给客户端,服务器本地不做存储,当前参考文档 https://www.workerman.net/doc/workerman/components/workerman-http-client.html 写的代码文件时下载下来了但是报文件是损坏的打不开,一下是具体代码

public function download(Request $request): \support\Response
{
    $url = $request->get('url');
    if (empty($url)) {
        return response_json(400, '参数不能为空');
    }
    $headers = get_headers($url, 1);

    if (!$headers || !str_contains($headers[0], '200')) {
        return response_json(400, 'URL不可访问', null, 403);
    }

    try {
        $connection = $request->connection;
        $http = new Client();
        $http->request($url, [
            'method' => 'GET',
            'progress' => function ($buffer) use ($connection) {
                $connection->send(new Chunk($buffer));
            },
            'success' => function ($response) use ($connection) {
                $connection->send(new Chunk('')); // 发送空的的chunk代表response结束
            },
        ]);
    } catch (\Throwable $e) {
        return response_json(500, $e->getMessage());
    }
    return response()->withHeaders([
        "Content-Type" => $headers['Content-Type'],
        "Transfer-Encoding" => "chunked",
    ]);
}
49 0 0
0个回答

×
🔝