123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446 |
- <?php
- namespace App\Traits;
- use App\Services\Ueditor\CrawlerAction;
- use App\Services\Ueditor\ListAction;
- use App\Services\Ueditor\UploadAction;
- use App\Services\UploaderService;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Str;
- use phpDocumentor\Reflection\Types\Boolean;
- use Txj\Elastic\Facades\ES;
- use Illuminate\Http\JsonResponse;
- use Illuminate\Http\UploadedFile;
- use Illuminate\Support\Facades\Request;
- trait UploadTrait
- {
- /**
- * 是否保存到数据库
- *
- * @var bool
- */
- public bool $isSaveToDb = true;
- /**
- * 保存的表
- *
- * @var string
- */
- public string $table = 'media_list';
- public bool $isRename = true; // 是否需要重命名
- /**
- * 上传图片
- */
- public function img()
- {
- $type = Request::post('type');
- $group_id = Request::post('group_id');
- if (empty($type)) {
- return responseMessage(2001, '请选择类型');
- }
- $upload = Request::file('file');
- if ($upload) {
- return $this->getUploadFilePath($upload, 'img', $group_id, ['png', 'jpg', 'jpeg', 'gif'], 2048000);
- } else {
- return responseMessage(2002, '上传失败,请重试!');
- }
- }
- /**
- * 文件上传
- *
- * @return JsonResponse
- */
- public function file()
- {
- $type = Request::post('type');
- $group_id = Request::post('group_id');
- if (empty($type)) {
- return responseMessage(2001, '请选择类型');
- }
- $this->isRename = false;
- $upload = Request::file('file');
- if ($upload) {
- return $this->getUploadFilePath($upload, 'file', $group_id, [], 300*1024*1000);
- } else {
- return responseMessage(2005, '上传失败,请重试!');
- }
- }
- /**
- * 上传
- *
- * @param UploadedFile $file
- * @param string $type
- * @param int $group_id
- * @param array $isAllowFileExtension
- * @param int $maxFileSize
- * @return JsonResponse
- */
- private function getUploadFilePath(UploadedFile $file, string $type, int $group_id, array $isAllowFileExtension = [], int $maxFileSize = 2048000): JsonResponse
- {
- $fileName = $file->getClientOriginalName();
- $size = $file->getSize();
- // 2.是否符合文件类型 getClientOriginalExtension 获得文件后缀名
- $fileExtension = $file->getClientOriginalExtension();
- if ($isAllowFileExtension && !in_array($fileExtension, $isAllowFileExtension)) {
- return responseMessage(3001, '该文件类型不支持上传!');
- }
- // 3.判断大小是否符合 2M
- $tmpFile = $file->getRealPath();
- if (filesize($tmpFile) >= $maxFileSize) {
- return responseMessage(3002, '该文件大小,超过允许的最大值!');
- }
- $upload_dir = $this->getUploadDir($type);
- $disk_dir = public_path('static/' . $upload_dir);
- if (!file_exists($disk_dir) || !is_dir($disk_dir)) {
- @mkdir($disk_dir, 0777, true);
- }
- // todo 是否需要重命名 通过软件可以对图片压缩
- if ($this->isRename) {
- $file_name = md5(microtime()) . '.' . $fileExtension;
- } else {
- $file_name = $fileName;
- }
- $file->move($disk_dir, $file_name);
- $path = '/static/' . $upload_dir . $file_name;
- switch ($type) {
- case 'img':
- $imgType = 1;
- break;
- case 'video':
- $imgType = 2;
- break;
- case 'audio':
- $imgType = 3;
- break;
- case 'file':
- $imgType = 4;
- break;
- default:
- return responseMessage(3003, '该文件类型不支持上传!');
- }
- return $this->saveDb([
- 'group_id' => $group_id,
- 'type' => $imgType,
- 'extension' => $fileExtension,
- 'size' => $size,
- 'filename' => $fileName,
- 'path' => $path
- ]);
- }
- /**
- * 上传视频
- *
- * @return JsonResponse
- */
- public function video(): JsonResponse
- {
- $type = Request::post('type');
- $group_id = Request::post('group_id');
- if (empty($type)) {
- return responseMessage(2001, '请选择类型');
- }
- $upload = Request::file('file');
- if ($upload) {
- return $this->getUploadFilePath($upload, 'video', $group_id, ['mp4', 'mov'], 2048000);
- } else {
- return responseMessage(2005, '上传失败,请重试!');
- }
- }
- /**
- * 上传音频
- */
- public function audio(): JsonResponse
- {
- $type = Request::post('type');
- $group_id = Request::post('group_id');
- if (empty($type)) {
- return responseMessage(2001, '请选择类型');
- }
- $upload = Request::file('audio');
- if ($upload) {
- return $this->getUploadFilePath($upload, 'audio', $group_id, ['mp3'], 2048000);
- } else {
- return responseMessage(2005, '上传失败,请重试!');
- }
- }
- /**
- * 上传图片base64
- *
- * @return String
- * @throws \Exception
- */
- public function upBase64()
- {
- $requestData = Request::all();
- $group_id = $requestData['group_id'] ?? '';
- $base64Data = $requestData['img'] ?? '';
- if (empty($base64Data)) {
- return responseMessage(2001, '上传失败');
- }
- //截取字符串
- $base64Data = preg_replace('/data:image\/png;base64,/is', '', $base64Data);
- $img = base64_decode($base64Data);
- if (empty($img)) {
- return responseMessage(2002, '上传失败');
- }
- $upload_dir = $this->getUploadDir('img');
- $disk_dir = public_path('static/' . $upload_dir);
- if (!file_exists($disk_dir) || !is_dir($disk_dir)) {
- @mkdir($disk_dir, 0777, true);
- }
- //移动文件
- $file_name = md5(microtime()) . '.png';
- $filePath = $disk_dir . '/' . $file_name;
- $path = $upload_dir . $file_name;
- if (!file_put_contents($filePath, $img)) { //移动失败
- return responseMessage(2003, '上传失败,请重试!');
- } else { //移动成功
- $imgType = 1;
- $fileExtension = 'png';
- return $this->saveDb([
- 'group_id' => intval($group_id),
- 'type' => $imgType,
- 'extension' => $fileExtension,
- 'size' => strlen($img),
- 'filename' => $file_name,
- 'path' => $path
- ]);
- }
- }
- /**
- * 裁剪图片
- */
- public function crop()
- {
- $requestData = Request::all();
- $imgId = $requestData['id'] ?? '';
- $x = $requestData['x'] ?? 0;
- $y = $requestData['y'] ?? 0;
- $w = $requestData['w'] ?? '';
- $h = $requestData['h'] ?? '';
- if (empty($imgId)) {
- return responseMessage(2001, '图片不存在!');
- }
- if (empty($w) || empty($h)) {
- return responseMessage(2002, '参数错误!');
- }
- //获取图片信息
- $imgInfo = ES::table('media_list')->getEsInfo($imgId);
- if (empty($imgInfo)) {
- return responseMessage(2003, '图片不存在!');
- }
- $path = $imgInfo['path'];
- if (file_exists(public_path('static/' . $path))) {
- $upload = new UploaderService(
- '',
- [
- 'filePath' => '/static' . $imgInfo['path'],
- 'thumb' => [
- [
- 'x' => $x,
- 'y' => $y,
- 'width' => $w,
- 'height' => $h,
- ]
- ]
- ], 'crop');
- if (isset($upload->thumbs[0])) {
- $info = $upload->thumbs[0];
- $imgType = 1;
- $path = $info['path'] ? '/' . trim($info['path'], '/static') : '';
- return $this->saveDb([
- 'group_id' => $imgInfo['group_id'],
- 'type' => $imgType,
- 'extension' => $imgInfo['extension'],
- 'size' => $info['metadata']['file.FileSize'] ?? 0,
- 'filename' => $imgInfo['filename'],
- 'path' => $path
- ]);
- } else {
- return responseMessage(2004, '操作失败,请重试!!');
- }
- } else {
- return responseMessage(2005, '图片不存在!');
- }
- }
- /**
- * 获取当前用户的唯一标识
- *
- * @param $type
- * @return string
- */
- private function getUploadDir($type)
- {
- return '/upload/' . substr($this->siteInfo['mid'], 2, 8) . '/' . $type . '/' . mt_rand(0, 99) . '/';
- }
- #################################################################################################################
- ##### 百度上传 #####################################################################################################
- #################################################################################################################
- public function ueditor()
- {
- $config_path = config_path('ueditor.json');
- $CONFIG = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents($config_path)), true);
- $action = Request::input('action');
- // 动态设置图片前缀,显示全路径
- $static_url = config('app.asset_url');
- $CONFIG = array_merge($CONFIG, [
- 'imageUrlPrefix' => $static_url,
- 'scrawlUrlPrefix' => $static_url,
- 'snapscreenUrlPrefix' => $static_url,
- 'catcherUrlPrefix' => $static_url,
- 'videoUrlPrefix' => $static_url,
- 'fileUrlPrefix' => $static_url,
- 'imageManagerUrlPrefix' => $static_url,
- 'fileManagerUrlPrefix' => $static_url,
- ]);
- switch ($action) {
- case 'config':
- $result = json_encode($CONFIG);
- break;
- /* 上传图片 */
- case 'uploadimage':
- /* 上传涂鸦 */
- case 'uploadscrawl':
- $result = (new UploadAction($CONFIG, $action))->doUpload();
- //保存到数据库
- $this->saveToDb(1, 'media_list', $result);
- break;
- /* 上传视频 */
- case 'uploadvideo':
- $result = (new UploadAction($CONFIG, $action))->doUpload();
- //保存到数据库
- $this->saveToDb(2, 'media_list', $result);
- break;
- /* 上传文件 */
- case 'uploadfile':
- $result = (new UploadAction($CONFIG, $action))->doUpload();
- //保存到数据库
- $this->saveToDb(4, 'media_list', $result);
- break;
- /* 列出图片 */
- case 'listimage':
- /* 列出文件 */
- case 'listfile':
- $result = (new ListAction($CONFIG, $action))->doList();
- break;
- /* 抓取远程文件 */
- case 'catchimage':
- $result = (new CrawlerAction($CONFIG, $action))->doCrawler();
- break;
- default:
- $result = json_encode(array(
- 'state' => '请求地址出错'
- ));
- break;
- }
- /* 输出结果 */
- if (isset($_GET["callback"])) {
- if (preg_match("/^[\w_]+$/", $_GET["callback"])) {
- echo htmlspecialchars($_GET["callback"]) . '(' . $result . ')';
- } else {
- echo json_encode(array(
- 'state' => 'callback参数不合法'
- ));
- }
- } else {
- echo $result;
- }
- die();
- }
- /**
- * 编辑器上传保存
- *
- * @param $type
- * @param $alias
- * @param $result
- * @return JsonResponse|void
- */
- private function saveToDb($type, $alias, $result)
- {
- $result = json_decode($result, true);
- if (empty($result) || !is_array($result)) {
- return;
- }
- return $this->saveDb([
- 'group_id' => 0,
- 'type' => $type,
- 'extension' => $result['original'] ?? '',
- 'size' => $result['size'] ?? 0,
- 'filename' => $result['original'] ?? '',
- 'path' => $result['url'] ?? ''
- ]);
- }
- /**
- * 保存到数据库
- *
- * @param $data
- * @return JsonResponse
- */
- private function saveDb($data): JsonResponse
- {
- if ($this->isSaveToDb) {
- $data['mid'] = Str::random(12);
- $data['created_at'] = time();
- $data['updated_at'] = time();
- // 保存数据库
- $isSuccess = DB::table($this->table)->insert($data);
- if ($isSuccess) {
- return responseMessage(1001, '恭喜你,上传成功!', $data['filename']);
- } else {
- return responseMessage(2003, '上传失败,请重试!');
- }
- } else {
- return responseMessage(1001, '恭喜你,上传成功!!', $data['filename']);
- }
- }
- }
|