This commit is contained in:
2021-09-07 16:14:44 +08:00
parent 968814bd57
commit e412f0681f
7 changed files with 144 additions and 84 deletions
-81
View File
@@ -1,81 +0,0 @@
<?php
namespace Server\Constrict;
use Kiri\Exception\NotFindClassException;
use ReflectionException;
use Psr\Http\Message\ResponseInterface;
/**
*
*/
class DownloadEmitter implements Emitter
{
const IMAGES = [
'png' => 'image/png',
'jpeg' => 'image/jpeg',
'gif' => 'image/gif',
'bmp' => 'image/bmp',
'ico' => 'image/vnd.microsoft.icon',
'tiff' => 'image/tiff',
'svg' => 'image/svg+xml',
];
/**
* @param mixed $response
* @param ResponseInterface $emitter
* @throws NotFindClassException
* @throws ReflectionException
*/
public function sender(mixed $response, ResponseInterface $emitter): void
{
$content = $emitter->getContent()->getData();
$explode = explode('/', $content['path']);
$response->header('Pragma', 'public');
$response->header('Expires', '0');
$response->header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
$response->header('Content-Disposition', 'attachment;filename=' . end($explode));
$response->header('Content-Type', $type = get_file_extension($content['path']));
if (!in_array($type, self::IMAGES)) {
$response->header('Content-Transfer-Encoding', 'binary');
} else {
$response->end(file_get_contents($content['path']));
return;
}
if ($content['isChunk'] === false) {
$response->sendfile($content['path']);
} else {
$this->chunk($content, $response);
}
}
/**
* @param $content
* @param $response
*/
private function chunk($content, $response): void
{
$resource = fopen($content['path'], 'r');
$state = fstat($resource);
$offset = $content['offset'];
$response->header('Content-length', $state['size']);
while ($file = fread($resource, $content['limit'])) {
$response->write($file);
fseek($resource, $offset);
if ($offset >= $state['size']) {
break;
}
$offset += $content['limit'];
}
$response->end();
}
}
+1 -1
View File
@@ -50,7 +50,7 @@ class Request implements RequestInterface
/**
* @param \Swoole\Http\Request $request
* @return array<Request, Response>
* @return array<RequestInterface, ResponseInterface>
*/
public static function create(\Swoole\Http\Request $request): array
{
+7 -1
View File
@@ -5,6 +5,7 @@ namespace Server\Constrict;
use Annotation\Inject;
use Psr\Http\Message\ResponseInterface;
use Server\RequestInterface;
use Server\SInterface\DownloadInterface;
use Swoole\Server;
@@ -41,7 +42,12 @@ class ResponseEmitter implements Emitter
$response->setStatusCode($emitter->getStatusCode());
$response->header('Server', 'swoole');
$response->header('Swoole-Version', swoole_version());
$response->end($emitter->getBody());
if (!($emitter instanceof DownloadInterface)) {
$response->end($emitter->getBody());
} else {
$emitter->dispatch($response);
}
}
}