ThinkPHP里无法输出图片 设置响应头

今天写了一个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论坛网友的一句话

框架的定义就是在于更快速、便捷地开发应用
如果我使用了某款框架还是需要自己去注意条条款款,然后定义或修正许多形式上的规范,那还用框架干嘛呢
本末倒置,鸡蛋里面挑骨头


__EOF__

本文作者织梦行云
本文链接https://www.cnblogs.com/cxfs/p/13546183.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   遗失的美好灬  阅读(433)  评论(0编辑  收藏  举报
编辑推荐:
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
阅读排行:
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)
历史上的今天:
2019-08-22 Larvel操作MongoDB(对内嵌数组增删改)
2019-08-22 PHP操作MongoDB
点击右上角即可分享
微信分享提示