FileController.php 8.4 KB
<?php

namespace App\Http\Controllers\File;

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

class FileController
{
    public $upload_img = [
        //设置静态缓存参数(304)
        'header' => [
            'Cache-Control' => 'max-age=2592000',
            'Pragma' => 'cache',
            'Expires' => "%Expires%", // cache 1 month
            'etag' => "%etag%",
            'Last-Modified' => "%Last-Modified%",
            'Content-Description' => 'File Transfer',
        ],
    ];
    public $path = '';

    public $config = '';

    public $uploads = '';

    public $request = '';

    public function __construct()
    {
        $this->request = request();
        $this->config = config('filesystems.disks.upload');
        $this->uploads = config('upload.default_file');
        $this->path = $this->config['root'].$this->uploads['path'].'/';
    }

    /**
     * @param  :(获取文件)$hash
     * @name   :index
     * @author :lyh
     * @method :post
     * @time   :2023/5/9 9:15
     */
    public function index($hash = '', $w = 1)
    {
        // 检查是否有修改日期或ETag头部
        if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) || isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
            header("HTTP/1.1 304 Not Modified");
            exit;
        }
        $file_model = new File();
        $info = $file_model->read(['hash' => $hash]);
        if ($info === false) {
            $this->response('指定文件不存在!', Code::USER_ERROR);
        }
        $path = $info['path'];
        if (!is_file($path)) {
            $this->response('指定文件已被系统删除!', Code::USER_ERROR);
        }
        $size = $info['size'];
        // 设置Content-Type头部
        $header['Content-Type'] = 'video/' . $info['type'];
        // 设置Accept-Ranges头部
        $header['Accept-Ranges'] = 'bytes';
        // 检查是否有范围请求
        if (isset($_SERVER['HTTP_RANGE'])) {
            $range = $_SERVER['HTTP_RANGE'];
            $ranges = explode('-', substr($range, 6));
            $start = intval($ranges[0]);
            $end = $size - 1;
            if (!empty($ranges[1])) {
                $end = intval($ranges[1]);
            }
            $length = $end - $start + 1;
            // 设置部分响应头部
            $header['Content-Length'] = $length;
            $header['Content-Range'] = 'bytes ' . $start . '-' . $end . '/' . $size;
            // 发送206 Partial Content状态码
            header('HTTP/1.1 206 Partial Content');
            header('Status: 206 Partial Content');
            header('Accept-Ranges: bytes');
            header('Content-Range: bytes ' . $start . '-' . $end . '/' . $size);
            // 读取部分内容并发送响应
            $file = fopen($path, 'rb');
            fseek($file, $start);
            $buffer = 1024 * 8; // 设置缓冲区大小
            while (!feof($file) && ($p = ftell($file)) <= $end) {
                if ($p + $buffer > $end) {
                    // 最后一块缓冲区
                    $buffer = $end - $p + 1;
                }
                echo fread($file, $buffer);
                flush(); // 将输出刷新到浏览器
            }
            fclose($file);
            exit;
        }
        // 无范围请求,发送完整文件
        $header['Content-Length'] = $size;
        $content = file_get_contents($path);
        // 发送完整响应
        foreach ($header as $name => $value) {
            header("$name: $value");
        }
        echo $content;
        exit;
    }

    /**
     * @remark :上传文件
     * @name   :upload
     * @author :lyh
     * @method :post
     * @time   :2023/6/17 16:32
     */
    public function upload() {
        $this->request->validate([
            'file'=>['required'],
        ],[
            'file.required'=>'必须填写',
        ]);
        $files = $this->request->file('file');

        if (empty($files)) {
            $this->response('没有上传的文件!', 400);
        }
        $type = $this->request->post('type', 'single');
        if ($type == 'multi') {
            return $this->multi($files);
        } else {
            return $this->single($files);
        }
    }

    /**
     * @param $files
     * @remark :单文件上传
     * @name   :single
     * @author :lyh
     * @method :post
     * @time   :2023/6/17 16:32
     */
    public function single($files){
        $hash = hash_file('md5', $files->getPathname());
        //查看文件是否存在
        $fileModel = new File();
        $file_hash = $fileModel->read(['hash'=>$hash]);
        if($file_hash !== false){
            return $this->response('资源',Code::SUCCESS,['file'=>$hash]);
        }
        $url = $this->path;
        $fileName = uniqid().rand(10000,99999).'.'.$files->getClientOriginalExtension();
        $res =  $files->move($url,$fileName);
        if ($res === false) {
            return $this->response($files->getError(), Code::USER_ERROR);
        }
        $data = [
            'path' => $url.$fileName,
            'created_at' => date('Y-m-d H:i:s',time()),
            'size' => $res->getSize(),
            'hash' => $hash,
            'type'=>$files->getClientOriginalExtension(),
        ];
        $rs = $fileModel->add($data);
        if ($rs === false) {
            return $this->response('添加失败', Code::USER_ERROR);
        }
        return $this->response('资源',Code::SUCCESS,['file'=>$hash]);
    }

    /**
     * @param $files
     * @remark :多文件上传
     * @name   :multi
     * @author :lyh
     * @method :post
     * @time   :2023/6/17 16:32
     */
    private function multi($files) {
        if (!is_array($files)) {
            $files = [$files];
        }
        $save_data = [];
        $data = [];
        foreach ($files as $file) {
            $fileModel = new File();
            $hash = hash_file('md5', $file->getPathname());
            $file_hash = $fileModel->read(['hash'=>$hash]);
            if($file_hash !== false){
                $data[] = $hash;
                continue;
            }
            $url = $this->path;
            $fileName = uniqid().rand(10000,99999).'.'.$files->getClientOriginalExtension();
            $res = $file->move($url,$fileName);
            if ($res === false) {
                return $this->response($file->getError(), Code::USER_ERROR);
            }
            $save_data[] = [
                'path' => $url.$fileName,
                'created_at' => date('Y-m-d H:i:s',time()),
                'size' => $res->getSize(),
                'hash' => $hash,
                'type'=>$files->getClientOriginalExtension(),
            ];
            $data[] = $hash;
        }
        $fileModel->insert($save_data);
        return $this->response('资源',Code::SUCCESS,['file'=>$data]);
    }

    /**
     * @param $msg
     * @param string $code
     * @param $data
     * @param $result_code
     * @param $type
     * @remark :统一返回接口
     * @name   :response
     * @author :lyh
     * @method :post
     * @time   :2023/6/17 16:33
     */
    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;
        $response =  response($result,$result_code,$this->header);
        throw new HttpResponseException($response);
    }

    /**
     * @param $data
     * @remark :参数处理
     * @name   :_extents
     * @author :lyh
     * @method :post
     * @time   :2023/6/17 16:32
     */
    protected function _extents($data) {

        if (empty($data) || !is_array($data)) {
            return empty($data) ? is_array($data) ? [] : '' : $data;
        }
        foreach ($data as $k => $v) {
            if (is_array($v)) {
                $data[$k] = $this->_extents($v);
            } else {
                if (is_null($v)) {
                    $data[$k] = '';
                    continue;
                }
                switch ((string) $k) {
                    case 'file':
                        $data['file_link'] = url('/b/file_hash/'.$v);
                        break;
                }
            }
        }
        return $data;
    }
}