明天写了一个PHP生成图片,想用浏览器查看,然而每次关上都是一串乱码,看样子是图片源二进制数据,而后查看了下响应头是text/html,那我明明设置了image/jpeg
header("Content-type", "image/jpeg");
这阐明TP默认设置了text/html,查了官网文档,啥也没说,去网上查,才晓得TP有个Response类,默认所有控制器输入text/html,官网文档啥也没说,只好本人去翻Response这个类了
ThinkPHP6\vendor\topthink\framework\src\think\Response.php
基类Response被这几个类继承,我试了下File类,然而这个File是输入文件,浏览器间接下载了
$file = new File('123.jpg');$response = $file->mimeType('image/jpeg');throw new HttpResponseException($response);
在看看基类Response
/** * 创立Response对象 * @access public * @param mixed $data 输入数据 * @param string $type 输入类型 * @param int $code 状态码 * @return Response */ public static function create($data = '', string $type = 'html', int $code = 200): Response { $class = false !== strpos($type, '\\') ? $type : '\\think\\response\\' . ucfirst(strtolower($type)); return Container::getInstance()->invokeClass($class, [$data, $code]); }
这里是主动找response目录下的响应类,但我只想设置一个响应头来显示我的图片,文档翻遍了没找到办法,而后看了看目录下的Html类,那咱们能够本人写一个自定义类来输入本人想要的响应格局
/** * Html Response */class Html extends Response{ /** * 输入type * @var string */ protected $contentType = 'text/html'; public function __construct(Cookie $cookie, $data = '', int $code = 200) { $this->init($data, $code); $this->cookie = $cookie; }}
于是我在response目录写了一个Jpeg类
/** * Html Response */class Jpeg extends Response{ /** * 输入type * @var string */ protected $contentType = 'image/jpeg'; public function __construct(Cookie $cookie, $data = '', int $code = 200) { $this->init($data, $code); $this->cookie = $cookie; }}
能够输入图片了
$response = Response::create('', 'Jpeg');$image->blob('JPEG');throw new HttpResponseException($response);
兴许有方法不必这么麻烦,然而TP官网文档啥也没有写,一下子也找不到其余办法,导致我的header()函数都没用了,这里援用ThinkPHP论坛网友的一句话
框架的定义就是在于更疾速、便捷地开发利用
如果我应用了某款框架还是须要本人去留神条条款款,而后定义或修改许多模式上的标准,那还用框架干嘛呢
轻重倒置,鸡蛋外面挑骨头