您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

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

2024/10/31 6:16:26发布21次查看
下面由thinkphp教程栏目给大家介绍thinkphp里无法输出图片,设置响应头方法,希望对需要的朋友有所帮助!
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论坛网友的一句话
框架的定义就是在于更快速、便捷地开发应用
如果我使用了某款框架还是需要自己去注意条条款款,然后定义或修正许多形式上的规范,那还用框架干嘛呢
本末倒置,鸡蛋里面挑骨头相关推荐:最新的10个thinkphp视频教程
以上就是解决thinkphp里无法输出图片问题(关于设置响应头)的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product