下面由thinkphp教程欄目給大家介紹ThinkPHP里無(wú)法輸出圖片,設(shè)置響應(yīng)頭方法,希望對(duì)需要的朋友有所幫助!
今天寫了一個(gè)PHP生成圖片,想用瀏覽器查看,但是每次打開(kāi)都是一串亂碼,看樣子是圖片源二進(jìn)制數(shù)據(jù),然后查看了下響應(yīng)頭是text/html,那我明明設(shè)置了image/jpeg
header("Content-type", "image/jpeg");
這說(shuō)明TP默認(rèn)設(shè)置了text/html,查了官方文檔,啥也沒(méi)說(shuō),去網(wǎng)上查,才知道TP有個(gè)Response類,默認(rèn)所有控制器輸出text/html,官方文檔啥也沒(méi)說(shuō),只好自己去翻Response這個(gè)類了
ThinkPHP6vendortopthinkframeworksrcthinkResponse.php
基類Response被這幾個(gè)類繼承,我試了下File類,但是這個(gè)File是輸出文件,瀏覽器直接下載了
$file = new File('123.jpg'); $response = $file->mimeType('image/jpeg'); throw new HttpResponseException($response);
在看看基類Response
/** * 創(chuàng)建Response對(duì)象 * @access public * @param mixed $data 輸出數(shù)據(jù) * @param string $type 輸出類型 * @param int $code 狀態(tài)碼 * @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]); }
這里是自動(dòng)找response目錄下的響應(yīng)類,但我只想設(shè)置一個(gè)響應(yīng)頭來(lái)顯示我的圖片,文檔翻遍了沒(méi)找到方法,然后看了看目錄下的Html類,那我們可以自己寫一個(gè)自定義類來(lái)輸出自己想要的響應(yīng)格式
/** * 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目錄寫了一個(gè)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官方文檔啥也沒(méi)有寫,一下子也找不到其他方法,導(dǎo)致我的header()函數(shù)都沒(méi)用了,這里引用ThinkPHP論壇網(wǎng)友的一句話
框架的定義就是在于更快速、便捷地開(kāi)發(fā)應(yīng)用
如果我使用了某款框架還是需要自己去注意條條款款,然后定義或修正許多形式上的規(guī)范,那還用框架干嘛呢
本末倒置,雞蛋里面挑骨頭