Today, I wrote a PHP generated image. I want to view it with the browser, but every time I open it, it is a string of random code. It looks like the binary data of the image source. Then I checked that the response header is text/html. Then I clearly set image/jpeg
header("Content-type", "image/jpeg");
This shows that TP sets text/html by default. After checking the official document, it didn't say anything. Only after checking online did you know that TP has a Response class. By default, all controllers output text/html. The official document didn't say anything, so you had to turn to the Response class yourself
ThinkPHP6\vendor\topthink\framework\src\think\Response.php
The base class Response is inherited by these classes. I tried the File class, but the File is an output File and the browser downloads it directly
$file = new File('123.jpg'); $response = $file->mimeType('image/jpeg'); throw new HttpResponseException($response);
Look at the base class Response
/** * Create Response object * @access public * @param mixed $data output data * @param string $type type of output * @param int $code Status 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]); }
Here is to automatically find the response class under the response directory, but I just want to set a response header to display my picture. After searching the document, I can't find a method, and then I look at the Html class under the directory. Then we can write a custom class to output the response format we want
/** * Html Response */ class Html extends Response { /** * Output type * @var string */ protected $contentType = 'text/html'; public function __construct(Cookie $cookie, $data = '', int $code = 200) { $this->init($data, $code); $this->cookie = $cookie; } }
So I wrote a Jpeg class in the response directory
/** * Html Response */ class Jpeg extends Response { /** * Output type * @var string */ protected $contentType = 'image/jpeg'; public function __construct(Cookie $cookie, $data = '', int $code = 200) { $this->init($data, $code); $this->cookie = $cookie; } }
You can output pictures
$response = Response::create('', 'Jpeg'); $image->blob('JPEG'); throw new HttpResponseException($response);
There may be a way not to be so troublesome, but the TP official document doesn't write anything, and I can't find other methods at once, which makes my header() function useless. Here is a quote from a netizen of ThinkPHP forum
The definition of framework is to develop applications more quickly and conveniently
If I use a framework, I still need to pay attention to the terms and conditions, and then define or modify many formal specifications, what else do I use the framework for
Put the cart before the horse and pick the bone in the egg