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",
    ]);
}
204 1 0
1个回答

不懂就问,为什么这个url不直接给前端下载

  • 大古 3天前

    "Content-Type" => $headers['Content-Type'],

  • RainLee1990 2天前

    因为要在小程序用,域名太多小程序的下载域名填写不全

  • 超高级的稻姬 1天前

    你是否在搜索nginx代理,搜索nginx proxy_pass可以解决你的大部分问题

×
🔝