ImageController.php 1.8 KB
<?php

namespace App\Http\Controllers;

use App\Enums\Common\Code;
use App\Models\Image as ImageModel;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Http\JsonResponse;

class ImageController
{
    /**
     * @name 统一返回参数
     * @return JsonResponse
     * @author :liyuhang
     * @method
     */
    public function response($msg = null,string $code = Code::SUCCESS,$data = [],$result_code = 200,$type = 'application/json'): JsonResponse
    {
        $code = Code::fromValue($code);
        $result = [
            'msg' => $msg == ' ' ? $code->description : $msg,
            'code' => $code->value,
            'data' => $this->_extents($data),
        ];
        $this->header['Content-Type'] = $type;
        $this->header['token'] = $this->token;
        $response =  response($result,$result_code,$this->header);;
        throw new HttpResponseException($response);
    }


    public function index($hash){
        if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) || isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
            header("HTTP/1.1 304 Not Modified");
            exit;
        }
        $imageModel = new ImageModel();
        $info = $imageModel->read(['hash'=>$hash]);
        if ($info === false) {
            $this->response('指定图片不存在!', 404);
        }
        $path = './../'.$info['path'];
        if (!is_file($path)) {
            $this->response('指定图片已被系统删除!', 404,$path);
        }
        $content = '';
        $last_modified_time = gmdate(time() + ((30 * 60 * 60 * 24))) . " GMT";
        $header = str_replace(['%Expires%', "%etag%", '%Last-Modified%'], [$last_modified_time, $hash, $last_modified_time], $this->config['header_cache']);
        $content = file_get_contents($path);
        $header['Content-Length'] = $info['size'];
        return response($content, 200, $header);
    }
}