我正在使用guzzle从url中检索图像。其中一些网址来自 s3。S3 对图像使用application/octet-stream
内容类型。我认为我无法访问fulfilled
回调中的$request
对象,因此我无法看到扩展名是否在 url 中。当内容类型为application/octet-stream
时,我有什么办法可以猜测fulfilled
回调中的扩展名吗?
<?php
function getExtension(Response $response) {
$contentType = explode(';', $response->getHeaderLine('Content-Type'), 2)[0];
$extensions = [
'image/png' => '.png',
'image/jpg' => '.jpg',
'image/jpeg' => '.jpeg',
'image/gif' => '.gif',
'image/tiff' => '.tiff',
'image/bmp' => '.bmp',
'application/octet-stream' => false
];
return $extensions[$contentType] ?? null;
}
$client = new Client();
$pool = new Pool($client, $requests, [
'concurrency' => 5,
'fulfilled' => function ($response) use ($zip) {
$ext = getExtension($response);
if (null === $ext) {
return;
}
if (false === $ext) {
// figure out the extension somehow
// $ext = ".foobar";
}
$id = Uuid::uuid4()->toString();
$filename = $id . $ext;
$zip->addFromString($filename, (string)$response->getBody());
},
'rejected' => function ($reason, $index) {
// no-op
}
]
);
$pool->promise()->wait();
不幸的是,在 Guzzle 6 中,我们失去了执行以下操作的能力: $response->getEffectiveUrl()
.
您所需要的只是将请求 url 写入响应标头的中间件(或处理程序)。 然后可以通过 $response->getHeader('myRequestUrlHeader')[0]
访问该 url