FileController.php 10.6 KB
<?php

namespace App\Http\Controllers\File;

use App\Enums\Common\Code;
use App\Models\File\File;
use App\Models\Project\Project;
use App\Services\CosService;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Cache;

class FileController
{
    public $path = '';//路径

    public $config = '';//存储默认配置

    public $request = '';//request

    public $param = '';//参数

    public $token = '';//token

    public $cache = '';//缓存数据
    public $upload_location = 1;
    public $file_type = [
        2 => 'other',//其他
        1 => 'video',//视频
        0 => 'file'//文件
    ];
    public function __construct()
    {
        $this->request = request();
        $this->param = $this->request->all();
        $this->config = config('filesystems.disks.upload');
        $this->uploads = config('upload.default_file');
        //获取当前登录用户详情
        $this->token = $this->request->header('token');
        $this->cache = Cache::get($this->token);
    }

    /**
     * @param  :(获取文件)$hash
     * @name   :index
     * @author :lyh
     * @method :post
     * @time   :2023/5/9 9:15
     */
    public function index($hash = '')
    {
        // 检查是否有修改日期或ETag头部
        if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) || isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
            header("HTTP/1.1 304 Not Modified");
            exit;
        }
        $fileModel = new File();
        $info = $fileModel->read(['hash' => $hash]);
        if ($info === false) {
            $this->response('指定文件不存在!', Code::USER_ERROR);
        }
        $path = $this->config['root'].'/'.$info['path'];
        if (!is_file($path)) {
            $this->response('指定文件已被系统删除!', Code::USER_ERROR);
        }
        $size = $info['size'];
        header("Content-Length: ".$size);
        // 设置Content-Type头部
        header("Content-Type: {$info['mime']}");
        readfile($path);
        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('没有上传的文件!');
        }
        $type = $this->request->post('type','single');
        $this->setUrl();
        if ($type == 'multi') {
            return $this->multi($files);
        } else {
            $size = $files->getSize();
            $file_type = $files->getClientOriginalExtension();
            $mime = $files->getMimeType();
            return $this->single($files);
        }
    }

    /**
     * @remark :单文件上传
     * @name   :single
     * @author :lyh
     * @method :post
     * @time   :2023/6/17 16:32
     */
    public function single(&$files){
        $hash = hash_file('md5', $files->getPathname());
        $name = $files->getClientOriginalName();
        //查看文件是否存在
        $fileModel = new File();
        $file_hash = $fileModel->read(['hash'=>$hash]);
        if($file_hash !== false){
            return $this->response('资源',Code::SUCCESS,$this->responseData($file_hash['path'], $name));
        }
        $url = $this->config['root'].$this->path;
        $fileName = uniqid().rand(10000,99999).'.'.$files->getClientOriginalExtension();
        //同步数据到cos
        if($this->upload_location == 1){
            $cosService = new CosService();
            $cosService->uploadFile($files,$this->path,$fileName);
        }else{
            $res =  $files->move($url,$fileName);
            if ($res === false) {
                return $this->response($files->getError(), Code::USER_ERROR);
            }
        }
        $this->saveMysql($fileModel,$files->getSize(),$files->getClientOriginalExtension(),$fileName,$hash,$this->upload_location,$files->getMimeType(),$name);
        return $this->response('资源',Code::SUCCESS,$this->responseData($this->path.'/'.$fileName, $name));
    }

    /**
     * @remark :保存数据库
     * @name   :saveMysql
     * @author :lyh
     * @method :post
     * @time   :2023/7/19 16:38
     */
    public function saveMysql(&$fileModel,$size,$image_type,$fileName,$hash,$is_cos = 0,$mime = '',$name=''){
        $data = [
            'path' => $this->path.'/'.$fileName,
            'created_at' => date('Y-m-d H:i:s',time()),
            'size' => $size,
            'hash' => $hash,
            'type'=>$image_type,
            'refer'=>$this->param['refer'] ?? 1,
            'is_cos'=>$is_cos,
            'mime'=>$mime,
            'name'=>$name,
        ];
        $rs = $fileModel->add($data);
        if ($rs === false) {
            return $this->response('添加失败', Code::USER_ERROR);
        }
        return true;
    }

    /**
     * @remark :多文件上传(暂时未用)
     * @name   :multi
     * @author :lyh
     * @method :post
     * @time   :2023/6/17 16:32
     */
    private function multi($files) {
        $data = [];
        foreach ($files as $file) {
            $fileModel = new File();
            $name = $file->getClientOriginalName();
            $hash = hash_file('md5', $file->getPathname());
            $file_hash = $fileModel->read(['hash'=>$hash]);
            if($file_hash !== false){
                $data[] = $this->responseData($file_hash['path'], $name);
                continue;
            }
            $url = $this->config['root'].'/'.$this->path;
            $file_type = $file->getClientOriginalExtension();
            $fileName = uniqid().rand(10000,99999).'.'.$file_type;
            //同步数据到cos
            if($this->upload_location == 1){
                $cosService = new CosService();
                $cosService->uploadFile($files,$this->path,$fileName);
            }else{
                $res =  $files->move($url,$fileName);
                if ($res === false) {
                    return $this->response($files->getError(), Code::USER_ERROR);
                }
            }
            $size = $file->getSize();
            $mime = $file->getMimeType();
            $this->saveMysql($fileModel,$size,$file_type,$fileName,$hash,$this->upload_location,$mime,$name);
            $data[] = $this->responseData($this->path.'/'.$fileName, $name);
        }
         $this->response('资源',Code::SUCCESS,$data);
    }


    /**
     * @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 = [
            'message' => $msg == ' ' ? $code->description : $msg,
            'code' => $code->value,
            'data' => $data,
        ];
        $this->header['Content-Type'] = $type;
        $response =  response($result,$result_code,$this->header);
        throw new HttpResponseException($response);
    }

    /**
     * @remark :文件下载
     * @name   :downLoad
     * @author :lyh
     * @method :post
     * @time   :2023/6/26 16:28
     */
    public function downLoad(){
        $file_model = new File();
        $info = $file_model->read(['path' => str_replace_url($this->param['path'])]);
        if ($info === false) {
            $this->response('指定文件不存在!', Code::USER_ERROR);
        }
        $fileUrl = getFileUrl($info['path'],$info['is_cos']);
//        $fileName = basename($fileUrl);  // 要保存的文件名
        // 设置响应头
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . $info['name'] . '"');
        // 下载文件
        readfile($fileUrl);
    }

    /**
     * @remark :保存路径
     * @name   :setUrl
     * @author :lyh
     * @method :post
     * @time   :2023/7/18 15:36
     */
    public function setUrl(){
        //A端上传
        if(isset($this->param['refer_type']) && $this->param['refer_type'] == 1){
            $this->path = $this->uploads['path_a'].'/'.$this->file_type[$this->param['refer']].'/'.date('Y-m');
        }else{
            //B端上传,upload_method 为 1时  强制上传到本地
            if(!isset($this->param['upload_method'])) {
                //根据项目上传标识区分上传到cos/本地
                $projectModel = new Project();
                $project_info = $projectModel->read(['id' => $this->cache['project_id']], ['project_location']);
                if ($project_info['project_location'] != 0) {//通项目时 上传到cos
                    $this->upload_location = 0;//1:上传到本地
                }
            }
            $this->path = $this->uploads['path_b'].'/'.$this->cache['project_id'].'/'.$this->file_type[$this->param['refer']].'/'.date('Y-m');
        }
    }

    /**
     * @remark :获取所有视频
     * @name   :getImageList
     * @author :lyh
     * @method :post
     * @time   :2023/6/29 11:48
     */
    public function getFileList(){
        if(isset($this->cache['project_id']) && !empty($this->cache['project_id'])){
            $this->map['project_id'] = $this->cache['project_id'];
        }
        $this->map['refer'] = 1;
        $fileModel = new File();
        $lists = $fileModel->list($this->map,'id',['id','hash','type','path','created_at','name']);
        foreach ($lists as $k => $v){
            $v['file_link'] = getFileUrl($v['path']);
            $lists[$k] = $v;
        }
        $this->response('success',Code::SUCCESS,$lists);
    }

    /**
     * @remark :统一返回参数处理
     * @name   :responseData
     * @author :lyh
     * @method :post
     * @time   :2023/7/26 13:41
     */
    public function responseData($path, $name){
        $data = [
            'file'=>$path,
            'file_link'=>getFileUrl($path,$this->upload_location),
            'name'=>$name,
        ];
        return $data;
    }

    /**
     * @remark :获取下载链接
     * @name   :getDownloadUrl
     * @author :lyh
     * @method :post
     * @time   :2023/7/26 14:00
     */
    public function getDownloadUrl(){
        $fileModel = new File();
        $info = $fileModel->read(['path' => str_replace_url($this->param['path'])]);
        if ($info === false) {
            $this->response('指定文件不存在!', Code::USER_ERROR);
        }
        $data = ['file_download'=>url('a/download_files?path='.$info['path']), 'name' => $info['name']];
        $this->response('success',Code::SUCCESS,$data);
    }
}