站长资讯网
最全最丰富的资讯网站

解决ThinkPHP里无法输出图片问题(关于设置响应头)

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

解决ThinkPHP里无法输出图片问题(关于设置响应头)

今天写了一个PHP生成图片,想用浏览器查看,但是每次打开都是一串乱码,看样子是图片源二进制数据,然后查看了下响应头是text/html,那我明明设置了image/jpeg

header("Content-type", "image/jpeg");

这说明TP默认设置了text/html,查了官方文档,啥也没说,去网上查,才知道TP有个Response类,默认所有控制器输出text/html,官方文档啥也没说,只好自己去翻Response这个类了

ThinkPHP6vendortopthinkframeworksrcthinkResponse.php

解决ThinkPHP里无法输出图片问题(关于设置响应头)

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

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

赞(0)
分享到: 更多 (0)

网站地图   沪ICP备18035694号-2    沪公网安备31011702889846号