Response类新增sendFile方法

This commit is contained in:
TOP糯米 2020-05-30 14:19:42 +08:00
parent 2c3e516310
commit cdd7799cac
4 changed files with 42 additions and 15 deletions

View File

@ -83,10 +83,10 @@ class Application
// 处理请求并得到数据
$response = Response::instance()->header([
'X-Powered-By: TOP-Framework'
'X-Powered-By: TOP-Framework',
])->send($router->execute());
// 响应内容
// 统一输出响应内容
echo $response->content;
}

View File

@ -0,0 +1,19 @@
<?php
namespace top\library\exception;
class ResponseException extends BaseException
{
public function __construct($message = "", $code = 0, \Throwable $previous = null)
{
parent::__construct('[ResponseException]' . $message, $code, $previous);
}
/**
* @param \Exception $exception
*/
public function handler($exception = null)
{
parent::handler($this); // TODO: Change the autogenerated stub
}
}

View File

@ -2,7 +2,6 @@
namespace top\library\http;
use top\library\Application;
use top\library\Router;
use top\traits\Instance;

View File

@ -2,7 +2,7 @@
namespace top\library\http;
use Exception;
use top\library\exception\ResponseException;
use top\library\View;
use top\traits\Instance;
use top\traits\Json;
@ -100,6 +100,7 @@ class Response
foreach ($this->header as $value) {
header($value);
}
return $this;
}
@ -118,7 +119,7 @@ class Response
'Status ' . $text,
]);
}
throw new Exception('不支持的状态码:' . $code);
throw new ResponseException('不支持的状态码:' . $code);
}
/**
@ -148,6 +149,23 @@ class Response
}
}
/**
* 输出文件
* @param $filename
* @param $name
* @return Response
*/
public function sendFile($filename = null, $name = null)
{
if (is_file($filename)) {
$name = ($name) ? $name : uniqid() . '.' . substr($filename, strrpos($filename, '.') + 1);
return $this->header([
'Content-Disposition: attachment; filename="' . $name . '"',
])->code(200)->send(readfile($filename));
}
throw new ResponseException('不存在的文件:' . $filename);
}
/**
* 处理数据
* @param $data
@ -173,13 +191,4 @@ class Response
return $data;
}
/**
* 直接echo处理
* @return string
*/
public function __toString()
{
return $this->content;
}
}