第一步:创建一个中间件
第二部:在中间件中写入代码:
//静态资源
$currUrl = trim($request->getUri()->getPath(), '/');
$extension = pathinfo($currUrl, PATHINFO_EXTENSION);
if (!empty($extension) && $extension !== 'php') {
//配置文件可看这里:https://www.hyperf.wiki/2.1/#/zh-cn/filesystem?id=%e9%85%8d%e7%bd%ae%e9%9d%99%e6%80%81%e8%b5%84%e6%ba%90
if (!config('server.settings.enable_static_handler')) {
throw new NotFoundHttpException();
}
//根据url拼接实际的保存路径
$static_file = config('server.settings.document_root').DIRECTORY_SEPARATOR.'upload' . DIRECTORY_SEPARATOR.'static'.DIRECTORY_SEPARATOR . $currUrl;
if (!is_file($static_file)) {
throw new NotFoundHttpException();
}
return Context::get(ResponseInterface::class)
->withHeader('Server', 'crashing')
->withBody(new SwooleFileStream($static_file));
}
return $handler->handle($request);