从没有文件名的 url 获取文件名和扩展名
Getting file name and extension from url's without filenames
我正在下载一个文件,稍后再将其上传到 API 以检查该文件是否是恶意文件。
起初很容易,如果文件名+扩展名在 URL 中,但看到情况并非总是如此,我不知道呈现给我的确切文件名和扩展名,所以尝试将其保存到临时文件时,我无法为其分配文件扩展名。
是否有可能以某种方式在响应中获取此文件名?或者至少是扩展名,这样我可以在再次上传之前将它添加到我的临时文件中..
这是我目前拥有的(我知道我目前只使用 tmp 文件名,但一旦我知道如何检查文件扩展名,这就会改变):
public function download($url, $tmpfilename, $method)
{
$client = new Client([
// Base URI is used with relative requests
'base_uri' => $url,
'sink' => $tmpfilename,
]);
try {
$response = $client->request($method);
if (is_bool($response)) {
return $response;
} else {
return $response->getBody()->getContents();
}
} catch (\GuzzleHttp\Exception\ClientException $e) {
return false;
} catch (\GuzzleHttp\Exception\RequestException $e) {
return false;
}
}
您可以使用 Content-Type
响应 header 猜测文件扩展名。
例如,用ralouphie/mimey做转换:
$extension = $mimes->getExtension($response->getHeaderLine('Content-Type'));
我正在下载一个文件,稍后再将其上传到 API 以检查该文件是否是恶意文件。
起初很容易,如果文件名+扩展名在 URL 中,但看到情况并非总是如此,我不知道呈现给我的确切文件名和扩展名,所以尝试将其保存到临时文件时,我无法为其分配文件扩展名。
是否有可能以某种方式在响应中获取此文件名?或者至少是扩展名,这样我可以在再次上传之前将它添加到我的临时文件中..
这是我目前拥有的(我知道我目前只使用 tmp 文件名,但一旦我知道如何检查文件扩展名,这就会改变):
public function download($url, $tmpfilename, $method)
{
$client = new Client([
// Base URI is used with relative requests
'base_uri' => $url,
'sink' => $tmpfilename,
]);
try {
$response = $client->request($method);
if (is_bool($response)) {
return $response;
} else {
return $response->getBody()->getContents();
}
} catch (\GuzzleHttp\Exception\ClientException $e) {
return false;
} catch (\GuzzleHttp\Exception\RequestException $e) {
return false;
}
}
您可以使用 Content-Type
响应 header 猜测文件扩展名。
例如,用ralouphie/mimey做转换:
$extension = $mimes->getExtension($response->getHeaderLine('Content-Type'));