Home>Article>PHP Framework> Solve the problem of being unable to output images in ThinkPHP (about setting response headers)

Solve the problem of being unable to output images in ThinkPHP (about setting response headers)

藏色散人
藏色散人 forward
2021-03-24 17:11:00 2993browse

下面由thinkphp教程栏目给大家介绍ThinkPHP里无法输出图片,设置响应头方法,希望对需要的朋友有所帮助!

Solve the problem of being unable to output images in ThinkPHP (about setting response headers)

今天写了一个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

Solve the problem of being unable to output images in ThinkPHP (about setting response headers)

基类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论坛网友的一句话

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

相关推荐:最新的10个thinkphp视频教程

The above is the detailed content of Solve the problem of being unable to output images in ThinkPHP (about setting response headers). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete