course/app/common/service/UploadService.php

118 lines
3.7 KiB
PHP
Raw Normal View History

<?php
namespace app\common\service;
use app\constant\ResponseCode;
use app\utils\QiniuUtils;
use think\Exception;
class UploadService
{
public function uploadImg($file)
{
ini_set('memory_limit', '256M');
try {
if ($file && $file->isValid()) {
$ext = $file->getUploadExtension();
if (in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'JPG', 'JPEG', 'PBG'])) {
$type = 'images';
} else {
$type = 'other';
}
$fileSize = $file->getSize();
$uploadDir = '/files/' . $type . '/' . date('Ym') . '/';
$filename = date('YmdHis') . rand(999, 99999);
$uploadPath = $uploadDir . $filename . '.' . $ext;
$rootUploadDir = public_path() . $uploadDir;
if (!is_dir($rootUploadDir)) {
mkdir($rootUploadDir, 0777, true);
}
$filePath = public_path() . $uploadPath;
$file->move($filePath);
//上传到七牛云
$res = QiniuUtils::upload($filePath);
2024-07-18 00:25:58 +08:00
if ($res['code'] == ResponseCode::FAIL) {
throw new Exception($res['msg']);
}
//删除本地图片
unlink($filePath);
return [
'code' => ResponseCode::SUCCESS,
'msg' => '上传成功',
'data' => $res['data']
];
2024-07-18 00:25:58 +08:00
} else {
throw new Exception('文件无效');
}
2024-07-18 00:25:58 +08:00
} catch (Exception $e) {
return [
'code' => ResponseCode::FAIL,
'msg' => $e->getMessage()
];
}
}
public function uploadFile($file)
{
ini_set('memory_limit', '256M');
try {
if ($file && $file->isValid()) {
$ext = $file->getUploadExtension();
2024-07-23 23:29:56 +08:00
if (in_array($ext, ['pdf', 'doc', 'docx', 'xlsx', 'xls', 'csv', 'pptx', 'ppt', 'zip', 'jpg', 'jpeg', 'png', 'gif', 'bmp', 'JPG', 'JPEG', 'PBG', 'txt'])) {
$type = 'files';
2024-07-18 00:25:58 +08:00
} else {
$type = 'other';
}
$fileSize = $file->getSize();
$origin_name = $file->getUploadName();
2024-07-18 00:25:58 +08:00
$uploadDir = '/files/' . $type . '/' . date('Ym') . '/';
$filename = date('YmdHis') . rand(999, 99999);
$uploadPath = $uploadDir . $filename . '.' . $ext;
$rootUploadDir = public_path() . $uploadDir;
if (!is_dir($rootUploadDir)) {
mkdir($rootUploadDir, 0777, true);
}
$filePath = public_path() . $uploadPath;
$file->move($filePath);
//上传到七牛云
$res = QiniuUtils::upload($filePath);
if ($res['code'] == ResponseCode::FAIL) {
throw new Exception($res['msg']);
}
2024-07-18 00:25:58 +08:00
//删除本地图片
unlink($filePath);
return [
'code' => ResponseCode::SUCCESS,
'msg' => '上传成功',
'data' => [
'url' => $res['data'],
'origin_name' => $origin_name
]
2024-07-18 00:25:58 +08:00
];
} else {
throw new Exception('文件无效');
}
} catch (Exception $e) {
return [
'code' => ResponseCode::FAIL,
'msg' => $e->getMessage()
];
}
}
}