Files
amb_wechatapp/application/api/controller/Upload.php
T

204 lines
7.5 KiB
PHP

<?php
namespace app\api\controller;
use app\common\controller\Api;
use think\Config;
use fast\Random;
use app\common\model\Attachment;
/**
* 上传接口
*/
class Upload extends Api
{
protected $noNeedLogin = [''];
protected $noNeedRight = ['*'];
/**
* 上传文件
* @ApiMethod (POST)
* @param File $file 文件流
*/
public function image()
{
$file = $this->request->file('file');
if (empty($file)) {
$this->error(__('No file upload or server upload limit exceeded'));
}
//判断是否已经存在附件
$sha1 = $file->hash();
$upload = Config::get('upload');
preg_match('/(\d+)(\w+)/', $upload['maxsize'], $matches);
$type = strtolower($matches[2]);
$typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
$size = (int)$upload['maxsize'] * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0);
$fileInfo = $file->getInfo();
$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']);
//禁止上传PHP和HTML文件
if (in_array($fileInfo['type'], ['text/x-php', 'text/html']) || in_array($suffix, ['php', 'html', 'htm'])) {
$this->error(__('Uploaded file format is limited'));
}
//验证文件后缀
if ($upload['mimetype'] !== '*' &&
(
!in_array($suffix, $mimetypeArr)
|| (stripos($typeArr[0] . '/', $upload['mimetype']) !== false && (!in_array($fileInfo['type'], $mimetypeArr) && !in_array($typeArr[0] . '/*', $mimetypeArr)))
)
) {
$this->error(__('Uploaded file format is limited'));
}
//验证是否为图片文件
$imagewidth = $imageheight = 0;
if (in_array($fileInfo['type'], ['image/gif', 'image/jpg', 'image/jpeg', 'image/bmp', 'image/png', 'image/webp']) || in_array($suffix, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'webp'])) {
$imgInfo = getimagesize($fileInfo['tmp_name']);
if (!$imgInfo || !isset($imgInfo[0]) || !isset($imgInfo[1])) {
$this->error(__('Uploaded file is not a valid image'));
}
$imagewidth = isset($imgInfo[0]) ? $imgInfo[0] : $imagewidth;
$imageheight = isset($imgInfo[1]) ? $imgInfo[1] : $imageheight;
}
$replaceArr = [
'{year}' => date("Y"),
'{mon}' => date("m"),
'{day}' => date("d"),
'{hour}' => date("H"),
'{min}' => date("i"),
'{sec}' => date("s"),
'{uniacid}'=>UNIACID,
'{random}' => Random::alnum(16),
'{random32}' => Random::alnum(32),
'{filename}' => $suffix ? substr($fileInfo['name'], 0, strripos($fileInfo['name'], '.')) : $fileInfo['name'],
'{suffix}' => $suffix,
'{.suffix}' => $suffix ? '.' . $suffix : '',
'{filemd5}' => md5_file($fileInfo['tmp_name']),
];
$savekey = $upload['savekey'];
$savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);
$uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
$fileName = substr($savekey, strripos($savekey, '/') + 1);
//
$splInfo = $file->validate(['size' => $size])->move(ROOT_PATH . '/public' . $uploadDir, $fileName);
if ($splInfo) {
$params = array(
'admin_id' => 0,
'user_id' => $this->auth->id,
'filesize' => $fileInfo['size'],
'imagetype' => $suffix,
'imageframes' => 0,
'mimetype' => $fileInfo['type'],
'url' => $uploadDir . $splInfo->getSaveName(),
'uploadtime' => time(),
'storage' => 'local',
'sha1' => $sha1,
);
$attachment = new \app\common\model\Attachment;
$attachment->data(array_filter($params));
$attachment->save();
$this->success(__('Upload successful'), [
'url' => $uploadDir . $splInfo->getSaveName(),
'full_url' => cdnurl($uploadDir . $splInfo->getSaveName())
]);
} else {
// 上传失败获取错误信息
$this->error($file->getError());
}
}
/**
* 上传 base64 图片
* @ApiMethod (POST)
* @param base64 内容
*/
public function uploadBase64()
{
$content = $this->request->post('content', '');
if (empty($content) || !preg_match('/^(data:\s*image\/(\w+);base64,)/', $content, $matches)) {
$this->error(__('No file upload or server upload limit exceeded'));
}
$upload = Config::get('upload');
$suffix = $matches[2]; //图片后缀
$mimetypeArr = explode(',', strtolower($upload['mimetype']));
// 判断是否允许的后缀
if ($upload['mimetype'] !== '*' && !in_array($suffix, $mimetypeArr)) {
$this->error(__('Uploaded file format is limited'));
}
$replaceArr = [
'{year}' => date("Y"),
'{mon}' => date("m"),
'{day}' => date("d"),
'{hour}' => date("H"),
'{min}' => date("i"),
'{sec}' => date("s"),
'{random}' => Random::alnum(16),
'{random32}' => Random::alnum(32),
'{filename}' => "店铺装修截图",
'{suffix}' => $suffix,
'{.suffix}' => $suffix ? '.' . $suffix : '',
'{filemd5}' => md5($content),
];
$savekey = $upload['savekey'];
$savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);
$uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
$fileName = substr($savekey, strripos($savekey, '/') + 1);
$fullDir = ROOT_PATH . '/public' . $uploadDir;
$uploadPath = $uploadDir . $fileName;
$fullPath = $fullDir . $fileName;
if (!is_dir($fullDir)) {
mkdir($fullDir, 0777, true);
}
$imageContent = base64_decode(str_replace($matches[1], '', $content));
if (file_put_contents($fullPath, $imageContent)) {
$imgInfo = getimagesize($fullPath);
$imagewidth = isset($imgInfo[0]) ? $imgInfo[0] : 0;
$imageheight = isset($imgInfo[1]) ? $imgInfo[1] : 0;
$params = array(
'admin_id' => 0,
'user_id' => (int)$this->auth->id,
'filesize' => strlen($content),
'imagewidth' => $imagewidth,
'imageheight' => $imageheight,
'imagetype' => $suffix,
'imageframes' => 0,
'mimetype' => isset($imgInfo['mime']) ? $imgInfo['mime'] : 'image/' . $suffix,
'url' => $uploadPath,
'uploadtime' => time(),
'storage' => 'local',
'sha1' => hash_file('sha1', $fullPath),
);
$attachment = new \app\common\model\Attachment;
$attachment->data(array_filter($params));
$attachment->save();
$this->success(__('Upload successful'), [
'url' => $uploadPath,
'full_url' => request()->domain() . $uploadPath
]);
} else {
$this->error("文件上传失败");
}
}
}