You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

92 lines
3.3 KiB

<?php
namespace app\service;
use think\facade\Config;
class UploadService extends BaseService
{
public function __construct() {
parent::__construct();
}
/**
* 上传文件
* @param mixed $filename 上传文件
* @param array|string[] $limitSuffix 限制后缀,默认允许所有后缀
* @param int $size 大小限制默认10m;单位b
* @return array
*/
public function uploadpic($filename, array $limitSuffix = ['*'], int $size = 0){
$path = "/pic";
if(is_string($filename)){
$file = request()->file($filename);
}else{
$file = $filename;
}
if(empty($file)){
throw new \think\Exception('没有上传的文件', 400);
}
$upload = config('upload');
$size = $size ?: ((int)$upload['maxsize'] * 1024 * 1024);
$fileInfo = [];
$fileInfo['name'] = $file->getOriginalName();
$fileInfo['type'] = $file->getOriginalMime();
$fileInfo['tmp_name'] = $file->getPathname();
$fileInfo['size'] = $file->getSize();
if($fileInfo['size'] > $size){
throw new \think\Exception('没有上传的文件', 400);
}
$suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
$suffix = $suffix && preg_match('/^[a-zA-Z0-9]+$/', $suffix) ? $suffix : 'file';
$mimetypeArr = explode(',', strtolower($upload['mimetype']));
$typeArr = explode('/', $fileInfo['type']);
if ($limitSuffix != ['*'] && !in_array($suffix, $limitSuffix)){
throw new \think\Exception('该文件类型不可上传', 400);
}
//禁止上传PHP和HTML文件
if (in_array($fileInfo['type'], ['text/x-php', 'text/html']) || in_array($suffix, ['php', 'html', 'htm'])) {
throw new \think\Exception('该文件类型不可上传', 400);
}
//验证文件后缀
if ($upload['mimetype'] !== '*' &&
(!in_array($suffix, $mimetypeArr) ||
(stripos($upload['mimetype'], $typeArr[1]) !== false &&
(!in_array($typeArr[1], $mimetypeArr))))) {
throw new \think\Exception('该文件类型不可上传', 400);
}
//验证是否为图片文件
$imagewidth = $imageheight = 0;
if (in_array($typeArr[1], explode('/', $fileInfo['type']))) {
$imgInfo = getimagesize($fileInfo['tmp_name']);
if (!$imgInfo || !isset($imgInfo[0]) || !isset($imgInfo[1])) {
throw new \think\Exception('不是图片文件', 400);
}
$imagewidth = isset($imgInfo[0]) ? $imgInfo[0] : $imagewidth;
$imageheight = isset($imgInfo[1]) ? $imgInfo[1] : $imageheight;
}
//上传图片
$savename = false;
try {
$savename = upload_file($file, 'public', $path); //保存用;存数据库不需要拼接Config::get('app.app_host')
$showname = trim(Config::get('app.cdnurl'), '/') . $savename; //展示用;
} catch (\Exception $e) {
$this->log->info($e->getMessage());
throw new \think\Exception('上传失败', 400);
}
return ['img' => $savename, 'show_img' => $showname];
}
}