|
|
<?php
namespace App\Service;
use App\Constants\ErrorCode;use League\Flysystem\FilesystemNotFoundException;
class AttachmentService implements AttachmentServiceInterface{
/** * @inheritDoc */ public function formUpload($file, $path, $filesystem, $attachmenttype = 'image') {
$fileRealPath = $file->getRealPath(); $fileHash = md5_file($fileRealPath);
$path = $this->getBasePath($path, $attachmenttype); $fileName = $path . '/' . $fileHash . '.' . $file->getExtension();
$stream = fopen($fileRealPath, 'r+'); $filesystem->writeStream($fileName, $stream); fclose($stream);
return $fileName; }
/** * @inheritDoc */ public function base64Upload($contents, $path, $filesystem) {
preg_match('/^(data:\s*image\/(\w+);base64,)/', $contents, $result); if (empty($result)) { throw new FilesystemNotFoundException(ErrorCode::getMessage(ErrorCode::UPLOAD_INVALID),ErrorCode::UPLOAD_INVALID); }
$contents = base64_decode(str_replace($result[1], '', $contents));
$fileHash = md5($contents); $path = $this->getBasePath($path); $fileName = $path . '/' . $fileHash . '.' . $result[2];
$filesystem->write($fileName, $contents);
return $fileName; }
protected function getBasePath($path, $attachmenttype = 'image') { switch ($attachmenttype) { case 'image': $baseDir = env('IMAGE_BASE', '/attachment/images'); break;
case 'file': $baseDir = env('FILES_BASE', '/attachment/files'); break;
default: $baseDir = env('FILES_BASE', '/attachment'); break; }
$path = $path ? '/'.$path : ''; $path .= '/'.date('Y').'/'.date('m').'/'.date('d'); return $baseDir.$path; }
public function switchImgToAliOss($path, $bucket = 'thumbnail_q50') { if (strpos($path, 'http') === false || strpos($path, 'https') === false) { $path = env('OSS_IMG_HOST') . '/' . $path; } else { $temp = explode('//', $path); $temp = explode('/', $temp[1]); unset($temp[0]); $path = env('OSS_IMG_HOST') . '/' . implode('/', $temp); } return $path . '!' . $bucket; }}
|