<?php
namespace startmvc\core;
class Upload {
public $maxSize = 2097152; public $exts = ['jpg', 'gif', 'png', 'jpeg'];
public $savePath = BASE_PATH.'upload';
public $urlPath = '/upload';
public $autoSub = true;
public $autoName = true;
public $replace = true;
public $fileName='';
function __construct(array $config = []) {
foreach ($config as $key => $value) {
if (property_exists($this, $key)) {
$this->$key = $value;
}
}
}
function upload() {
$results = [];
foreach ($_FILES as $file) {
if (is_array($file['name'])) {
foreach ($file['name'] as $key => $value) {
$fileInfo = [];
foreach ($file as $k => $v) {
$fileInfo[$k] = $v[$key];
}
$results[] = $this->file($fileInfo);
}
} else {
$results[] = $this->file($file);
}
}
return $results;
}
private function file($file) {
if ($file['error'] !== UPLOAD_ERR_OK) {
return ['result' => false, 'error' => '文件上传错误: ' . $file['error']];
}
$fileExt = pathinfo($file['name'], PATHINFO_EXTENSION);
if (!in_array($fileExt, $this->exts)) {
return ['result' => false, 'error' => '无效的文件扩展名'];
}
$saveDir = rtrim($this->savePath, '/') . '/';
$saveUrl = rtrim($this->urlPath, '/') . '/';
if ($this->autoSub) {
$subDir = date('Y/m/d');
$saveDir .= $subDir;
$saveUrl .= $subDir;
}
if (!is_dir($saveDir)&&!mkdir($saveDir, 0755, true)) {
return ['result' => false, 'error' => '创建目录失败'];
}
$filename = $this->fileName !== '' ? $this->fileName.'.'. $fileExt : ($this->autoName ? uniqid() . '.' . $fileExt : $file['name']);
$filePath = $saveDir . '/' . $filename;
$urlPath = $saveUrl . '/' . $filename;
if (!$this->replace && file_exists($filePath)) {
return ['result' => false, 'error' => '文件已经存在'];
}
if (!move_uploaded_file($file['tmp_name'], $filePath)) {
return ['result' => false, 'error' => '移动上传文件失败'];
}
return ['result' => true, 'url' => $urlPath,'filename'=>$filename];
}
}