分享一个自己写的上传类
<?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];
}
}
还没全部写完,后面会接着发
建议分两步哈, 文件上次 仅仅上传。其他的 hash 什么的,可以异步去做。