分享一个自己写的上传类

<?php

namespace App;
use Illuminate\Support\Facades\Storage;

class Upload
{
    protected $config;
    protected $extension;
    protected $clientMimeType;
    protected $hash = [];
    protected $realPath;

    public function __construct($file, $configName)
    {
        $this->config         = config('upload.' . $configName);
        $this->size           = $file->getClientSize();
        $this->extension      = $file->extension(); // 真实文件扩展名
        $this->clientMimeType = $file->getClientMimeType(); 
        $this->realPath       = $file->getRealPath();
    }

    // 获取文件的哈希散列值
    public function hash($type = 'sha1')
    {
        if (!isset($this->hash[$type])) {
            $this->hash[$type] = hash_file($type, $this->realPath);
        }

        return $this->hash[$type];
    }

    // 获取保存文件名
    protected function buildSaveName($name, $rule = 'date')
    {
        // 自动生成文件名
        if (true === $name) {
            if ($rule === 'date') {
                $name = date('Ymd') . DIRECTORY_SEPARATOR . md5(microtime(true));
            } else {
                if (in_array($rule, hash_algos())) {
                    $hash = $this->hash($rule);
                    $name = substr($hash, 0, 2) . DIRECTORY_SEPARATOR . substr($hash, 2);
                } else if (is_callable($rule)) {
                    $name = call_user_func($rule);
                }
            }
        }

        if (!strpos($name, '.')) {
            $name .= '.' . $this->extension;
        }

        if (isset($this->config['directory']) && !empty($this->config['directory'])) {
            return $this->config['directory'] . DIRECTORY_SEPARATOR . $name;
        }

        return $name;
    }

    public function checkExtension()
    {
        $ext = $this->config['ext'];
        if (is_string($ext)) {
            $ext = explode(',', $ext);
        }

        return in_array_case($this->extension, $ext);
    }

    public function checkSize() {
        return $this->size <= $this->config['size'];
    }

    public function save($saveName = true) {

        Storage::disk($this->config['disk'])->put($this->buildSaveName($saveName, $this->config['rule']), file_get_contents($this->realPath));

        // return ['name' => 'name.jpg', 'id' => 1, 'path' => 'path', 'md5' => 'md5', 'status' => true];
    }
}

还没全部写完,后面会接着发

《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 1

建议分两步哈, 文件上次 仅仅上传。其他的 hash 什么的,可以异步去做。

5年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!