我试图在不使用扩展程序的情况下链接图像,因为它使我更容易维护所有客户端文件。
当浏览器呈现页面时, assets/images/client
应解析为assets/images/client.png
。
在Slim中,它认为这些是路线而不是处理图像。有什么方法可以通过Slim处理/assets
来处理任何事情,让它只是通过常规的http请求吗?
答案 0 :(得分:1)
考虑使用Slim返回这些图像,它会保留您手中的控制权:您可以随时更改路径或包含文件夹。您还可以设置其他标头,例如用于缓存。
$app->get('/assets/images/{pathToClientImage}', function($request, $response, $args) {
$pathToFile = $args['pathToClientImage'];
$containingFolder = '../clients_images/'; // the actual folder where files are stored
// since you want to omit file extension in the url, we'll have to find the file
$matches = glob($containingFolder.$fileName.'.*');
if ($matches) {
$clientImagePath = array_shift($matches); // let's grab the first file matching our mask
$clientImage = @file_get_contents($clientImagePath);
$finfo = new \Finfo(FILEINFO_MIME_TYPE);
$response->write($clientImage);
return $response->withHeader('Content-Type', $finfo->buffer($clientImage));
} else {
// if no matches found, throw exception that will be handled by Slim
throw new \Slim\Exception\NotFoundException($request, $response);
}
});
如果您可以接受assets/images/client.png
(具有文件扩展名)等网址,则可以通过更简单的方式执行此操作:
$app->get('/assets/images/{pathToClientImage}', function($request, $response, $args) {
$pathToFile = $args['pathToClientImage'];
$path = '../clients_images/'.$fileName;
$image = @file_get_contents($path);
$finfo = new \Finfo(FILEINFO_MIME_TYPE);
$response->write($image);
return $response->withHeader('Content-Type', $finfo->buffer($image));
});