ImageLogic.php 4.2 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;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;

class ImageLogic
{
    public $path = '';

    public $request = '';

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

    /**
     * 图片上传
     */
    public function upload() {
        $this->request->validate([
            'image'=>['required'],
        ],[
            'image.required'=>'图片必须填写',
        ]);
        $files = $this->request->file('image');
        if (empty($files)) {
            $this->response('没有上传的文件!', 400);
        }
        $type = $this->request->post('type', 'single');
        if ($type == 'multi') {
            return $this->multi($files);
        } else {
            return $this->single($files);
        }
    }
    /**
     * @name :上传图片
     * @return void
     * @author :liyuhang
     * @method
     */
    public function single($files){
        $hash = hash_file('md5', $files->getPathname());
        $url = $this->path;
        $filename = date('ymdHis').rand(10000,99999);
        $res =  $this->request->file('image')->move($url,$filename);
        if ($res === false) {
            return $this->response($files->getError(), Code::USER_ERROR);
        }
        $imageModel = new ImageModel();
        $data = [
            'path' => $url.$filename,
            'created_at' => date('Y-m-d H:i:s',time()),
            'size' => $res->getSize(),
            'hash' => $hash.$filename,
            'type'=>$files->getClientOriginalExtension(),
        ];
        $rs = $imageModel->add($data);
        if ($rs === false) {
            return $this->response('添加失败', Code::USER_ERROR);
        }
        return $hash.$filename;
    }
    /**
     * 生成缩略图缓存
     * @param type $info
     * @param type $w
     * @param type $h
     * @return string
     */
    private function cacheImage($info, $w, $h) {
        $path = $info['path'];
        $filename = $this->path . $info['hash'] . $w . '_' . $h;
        Image::make($path)->resize($w, $h)->save($filename);
        return $filename;
    }

    /**
     * 多图片上传
     * @param type $files file对象集合
     * @return type
     */
    private function multi($files) {
        if (!is_array($files)) {
            $files = [$files];
        }
        $save_data = [];
        $data = [];
        foreach ($files as $file) {
            $hash = hash_file('md5', $file->getPathname());
            $url = $this->path;
            $filename = date('ymdHis').rand(10000,99999);
            $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.$filename,
                'type'=>$files->getClientOriginalExtension(),
            ];
            $data[] = $hash.$filename;
        }
        $imageModel = new ImageModel();
        $imageModel->insert($save_data);
        return $data;
    }

    //下载
    public function download($filename){
        $path = Storage::path($filename);
        return response()->download($path,time().rand(1,100000));
    }
    /**
     * @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' => $data,
        ];
        $this->header['Content-Type'] = $type;
        $response =  response($result,$result_code,$this->header);
        throw new HttpResponseException($response);
    }
}