mirror of
https://github.com/grocy/grocy.git
synced 2026-03-28 07:39:25 +01:00
Get the image file type from the response content type
When using the external lookup tool, the file extention in the URL is used for the name of the downloaded image. However, some API's do not use file types in the resource name. If that is the case, the Content-Type of the request will now be used to define the file extention.
This commit is contained in:
parent
4c5fbffd25
commit
3ebe1a93de
|
|
@ -630,7 +630,36 @@ class StockService extends BaseService
|
|||
{
|
||||
$webClient = new Client();
|
||||
$response = $webClient->request('GET', $pluginOutput['__image_url'], ['headers' => ['User-Agent' => 'Grocy/' . $this->getApplicationService()->GetInstalledVersion()->Version . ' (https://grocy.info)']]);
|
||||
$fileName = $pluginOutput['__barcode'] . '.' . pathinfo(parse_url($pluginOutput['__image_url'], PHP_URL_PATH), PATHINFO_EXTENSION);
|
||||
|
||||
$fileType = pathinfo(parse_url($pluginOutput['__image_url'], PHP_URL_PATH), PATHINFO_EXTENSION);
|
||||
|
||||
// Some API's don't use the filetype in the URL. In this case, use the content type in the headers.
|
||||
if ($fileType == '') {
|
||||
|
||||
// If the Content-Type does not exist, do not save the image.
|
||||
if (!$response->hasHeader('Content-Type')) {
|
||||
throw new \Exception('Image lookup response for product "' . $pluginOutput['name'] . '" does not have a Content-Type.');
|
||||
}
|
||||
|
||||
$contentType = $response->getHeader('Content-Type')[0]; // e.g. image/jpeg
|
||||
$contentTypeSplit = explode('/', $contentType);
|
||||
|
||||
// If the Content-Type is not an image, do not save the image.
|
||||
if ($contentTypeSplit[0] != 'image') {
|
||||
throw new \Exception('Image lookup response for product "' . $pluginOutput['name'] . '" does not have a Content-Type image/xxxx.');
|
||||
}
|
||||
|
||||
if ($contentType == 'image/svg+xml') {
|
||||
// SVG needs special handling
|
||||
$fileType = 'svg';
|
||||
} else {
|
||||
// Use the content type as file extension
|
||||
$fileType = $contentTypeSplit[1]; // e.g. jpeg
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
$fileName = $pluginOutput['__barcode'] . '.' . $fileType;
|
||||
file_put_contents($this->getFilesService()->GetFilePath('productpictures', $fileName), $response->getBody());
|
||||
$productData['picture_file_name'] = $fileName;
|
||||
}
|
||||
|
|
@ -1794,4 +1823,4 @@ class StockService extends BaseService
|
|||
$shoppingListRow = $this->getDatabase()->shopping_lists()->where('id = :1', $listId)->fetch();
|
||||
return $shoppingListRow !== null;
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user