根據(jù)url直接獲取文件流發(fā)送給客戶端,服務(wù)器本地不做存儲,當(dāng)前參考文檔 http://www.wtbis.cn/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, '參數(shù)不能為空');
}
$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('')); // 發(fā)送空的的chunk代表response結(jié)束
},
]);
} catch (\Throwable $e) {
return response_json(500, $e->getMessage());
}
return response()->withHeaders([
"Content-Type" => $headers['Content-Type'],
"Transfer-Encoding" => "chunked",
]);
}