cqp 3 месяцев назад
Родитель
Сommit
59e6457d10

+ 45 - 0
app/Http/Controllers/Api/FileUploadController.php

@@ -0,0 +1,45 @@
+<?php
+namespace App\Http\Controllers\Api;
+
+use App\Service\FileUploadService;
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Storage;
+use PhpOffice\PhpSpreadsheet\Calculation\Statistical\Distributions\F;
+
+//文件上传
+class FileUploadController extends BaseController
+{
+    public function uploadFile(Request $request){
+        $service = new FileUploadService();
+        list($status,$data) = $service->uploadFile($request->file('file'));
+
+        if($status){
+            return $this->json_return(200,'上传成功',['url' => $data]);
+        }else{
+            return $this->json_return(201,$data);
+        }
+    }
+
+    //获取文件的位置预览(临时文件)
+    public function getFile($file_name){
+        $file_name = str_replace(FileUploadService::string2,'',$file_name);
+        $timestamp = substr($file_name, 0, 8); // 截取前八位数字
+        $date = \DateTime::createFromFormat('Ymd', $timestamp);
+        $date = $date->format('Y-m-d');
+        $dir = FileUploadService::tmp_dir . '/' . $date. '/' . $file_name;
+        $path = storage_path() . "/app/public/" . $dir;
+
+        // 返回一个错误响应或默认图片
+        if (! Storage::disk('public')->exists($dir)) return $this->json_return(201,'File not exists');
+
+        return response()->file($path);
+    }
+
+    //获取文件的位置
+    public function getFileLocal($file_name){
+        $path = storage_path() . "/app/public/upload_files/".$file_name;
+        if(file_exists($path)) return response()->file($path);
+
+        return "";
+    }
+}

+ 169 - 0
app/Service/FileUploadService.php

@@ -0,0 +1,169 @@
+<?php
+
+namespace App\Service;
+
+
+use Illuminate\Support\Facades\Storage;
+
+class FileUploadService extends Service
+{
+    //文件类型
+    const FILE_TYPE = [
+        'txt',
+        'jpg',
+        'png',
+        'gif',
+        'jpeg',
+        'zip',
+        'rar',
+        'xlsx',
+        'xls',
+    ];
+
+    //视频类型
+    const VIDEO_FILE_TYPE = [
+        'mp4',
+    ];
+
+    const tmp_dir = 'upload_occ';
+    const string = '/api/uploadFiles/';
+    const string2 = 'work_hour|';
+    const string3 = 'work_hour/';
+
+    public function uploadFile($file){
+        if(empty($file)) return [false, '请上传文件'];
+        // 获取文件相关信息
+        $ext = $file->getClientOriginalExtension();     // 扩展名
+        $realPath = $file->getRealPath();   //临时文件的绝对路径
+
+        $ext = strtolower($ext);
+        $file_type = array_merge_recursive(self::FILE_TYPE, self::VIDEO_FILE_TYPE);
+        if (! in_array($ext, $file_type)){
+            $str = '文件格式支持类型:';
+            foreach ($file_type as $value){
+                $str.= $value . ' ' ;
+            }
+            return [false, $str];
+        }
+
+        if (in_array($ext, self::VIDEO_FILE_TYPE)) {
+            $fileSize = $file->getSize(); // 获取文件大小(单位:字节)
+            $maxVideoSize = 50 * 1024 * 1024; // 50 MB
+            if ($fileSize > $maxVideoSize) {
+                return [false, '视频文件大小不能超过 50MB'];
+            }
+        }
+
+        $date = date("Y-m-d");
+        //文件名
+        $file_name = date("Ymd").time().rand(1000,9999);
+        $filename =  $file_name.'.' . $ext;
+
+        $dir = self::tmp_dir . '/' . $date . '/' . $filename;
+        Storage::disk('public')->put($dir, file_get_contents($realPath));
+
+        return [true, self::string . self::string2 . $filename];
+    }
+
+    //获取文件的位置oss
+    public function getFileShow($file_name,$expired = 3500){
+        $path = "";
+        if(empty($file_name)) return $path;
+
+        $document = self::string3;
+        if(strpos($file_name, FileUploadService::string . FileUploadService::string2) !== false){
+            $file_name = str_replace(FileUploadService::string . FileUploadService::string2,'', $file_name);
+            $timestamp = substr($file_name, 0, 8); // 截取前八位数字
+            $date = \DateTime::createFromFormat('Ymd', $timestamp);
+            $date = $date->format('Y-m-d');
+            $savePath = $document . $date . '/' . $file_name;
+            list($status,$path) = (new OssService())->getTemporaryUrl($savePath,$expired);
+        }
+
+        return $path;
+    }
+
+    public function uploadFileLocal($file){
+        if(empty($file)) return [false, '请上传文件'];
+        // 获取文件相关信息
+        $ext = $file->getClientOriginalExtension();     // 扩展名
+        $realPath = $file->getRealPath();   //临时文件的绝对路径
+
+        $ext = strtolower($ext);
+        if (! in_array($ext, self::FILE_TYPE)){
+            $str = '文件格式为:';
+            foreach (self::FILE_TYPE as $value){
+                $str.= $value . ' ' ;
+            }
+            return [false,$str];
+        }
+
+        // 上传文件
+        $file_name = date("Ymd").time().rand(1000,9999);
+        $filename =  $file_name.'.' . $ext;
+        // 使用我们新建的uploads本地存储空间(目录)
+        Storage::disk('public')->put('upload_files/'.$filename, file_get_contents($realPath));
+
+        return [true, self::string . $filename];
+    }
+
+    public function createOssUpload($file){
+        if(! is_array($file) || empty($file)) return;
+        foreach ($file as $filename){
+            $filename = str_replace(FileUploadService::string.FileUploadService::string2,'', $filename);
+            $timestamp = substr($filename, 0, 8); // 截取前八位数字
+            $date = \DateTime::createFromFormat('Ymd', $timestamp);
+            $date = $date->format('Y-m-d');
+            $dir = FileUploadService::tmp_dir . '/' . $date . '/' . $filename;
+            if(Storage::disk('public')->exists($dir)){
+                $realPath = storage_path() . "/app/public/" . $dir;
+                $savePath = self::string3 . $date . '/' . $filename;
+                list($status,$msg) = (new OssService())->uploadFile($realPath,$savePath);
+                if($status) Storage::disk('public')->delete($dir);
+            }
+        }
+    }
+
+    public function createOssUploadOld($file){
+        if(! is_array($file) || empty($file)) return;
+
+        foreach ($file as $filename){
+            if(strpos($filename, FileUploadService::string.FileUploadService::string2) !== false){
+                $filename = str_replace(FileUploadService::string.FileUploadService::string2,'',$filename);
+                $timestamp = substr($filename, 0, 8); // 截取前八位数字
+                $date = \DateTime::createFromFormat('Ymd', $timestamp);
+                $date = $date->format('Y-m-d');
+                $delPath = self::string3 . $date . '/' . $filename;
+
+                list($status,$msg) = (new OssService())->deleteFile($delPath);
+//                if(! $status) return [false , $msg];
+            }else{
+                if(strpos($filename, FileUploadService::string) !== false){
+                    $filename = str_replace(FileUploadService::string,'',$filename);
+                    $delPath = self::string3 . 'old/upload_files/' . $filename;
+                    list($status,$msg) = (new OssService())->deleteFile($delPath);
+                }
+            }
+        }
+    }
+
+    public function createOssUploadBatch($file){
+        if(empty($file['origin']) || empty($file['img_list'])) return;
+        $from = $file['origin'];
+        $filename = str_replace(FileUploadService::string.FileUploadService::string2,'', $from);
+        $timestamp = substr($filename, 0, 8); // 截取前八位数字
+        $date = \DateTime::createFromFormat('Ymd', $timestamp);
+        $date = $date->format('Y-m-d');
+        $dir = FileUploadService::tmp_dir . '/' . $date . '/' . $filename;
+        if(! Storage::disk('public')->exists($dir)) return;
+
+        $realPath = storage_path() . "/app/public/" . $dir;
+        foreach ($file['img_list'] as $filename){
+            $filename_tmp = str_replace(FileUploadService::string.FileUploadService::string2,'', $filename);
+            $savePath = self::string3 . $date . '/' . $filename_tmp;
+            list($status,$msg) = (new OssService())->uploadFile($realPath,$savePath);
+        }
+
+        Storage::disk('public')->delete($dir);
+    }
+}

+ 156 - 0
app/Service/OssService.php

@@ -0,0 +1,156 @@
+<?php
+
+namespace App\Service;
+
+use Illuminate\Support\Facades\Cache;
+use OSS\Core\OssException;
+use OSS\OssClient;
+
+class OssService extends Service
+{
+    protected $accessKeyId;
+    protected $accessKeySecret;
+    protected $endpoint;
+    protected $bucket;
+
+    public function __construct()
+    {
+        $this->accessKeyId = config('aliyun.accessKeyId');
+        $this->accessKeySecret = config('aliyun.accessKeySecret');
+        $this->endpoint = config('aliyun.endpoint');
+        // 存储空间名称
+        $this->bucket = config('aliyun.ossBucket');
+    }
+
+    /**
+     * @desc 添加文件
+     * @param $filePath 上传的文件
+     * @param $savePath 保存到oss的路径
+     */
+    public function uploadFile($filePath, $savePath)
+    {
+        try {
+            $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
+            $ossClient->uploadFile($this->bucket, $savePath, $filePath);
+        } catch (OssException $e) {
+            return [false, $e->getMessage()];
+        }
+        return [true, ''];
+    }
+
+    /**
+     * @desc 删除文件
+     * @param deletePath oss的路径
+     */
+    public function deleteFile($deletePath)
+    {
+        try {
+            $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
+            $ossClient->deleteObject($this->bucket, $deletePath);
+        } catch (OssException $e) {
+            return [false, $e->getMessage()];
+        }
+        return [true, ''];
+    }
+
+    /**
+     * @desc 下载文件
+     * @param string $downLoadFile 下载文件地址
+     * @param string $saveFile 保存地址
+     */
+    public function downLoadFile($downLoadFile, $saveFile)
+    {
+        $localfile = $saveFile;
+        $options = array(
+            OssClient::OSS_FILE_DOWNLOAD => $localfile
+        );
+        try {
+            $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
+            $ossClient->getObject($this->bucket, $downLoadFile, $options);
+        } catch (OssException $e) {
+            return [false, 'msg' => $e->getMessage()];
+        }
+        return [true, ''];
+    }
+
+    //生成临时文件
+    public function getTemporaryUrl1($objectKey, $expired = 3500)
+    {
+        $timeStamp = time();
+
+        // 定义本地文件日志路径
+        $localFilePath = storage_path('app/public/oss_file/' . md5($objectKey) . '.txt');
+
+        $directoryPath = dirname($localFilePath);
+        // 检查目录是否存在,如果不存在则创建
+        if (! is_dir($directoryPath)) {
+            // 设置目录权限,可以根据需要更改
+            $mode = 0777;
+            // 使用递归选项创建目录
+            if (!mkdir($directoryPath, $mode, true)) return [false, '目录创建失败'];
+        }
+
+        $url = "";
+        $timestamp = $timeStamp + $expired;
+        if(! file_exists($localFilePath)){
+            $url = $this->createUrl($objectKey,$expired);
+            $set = [
+                'url' => $url,
+                'timestamp' => $timestamp,
+            ];
+            file_put_contents($localFilePath, json_encode($set));
+        }else{
+            $content = file_get_contents($localFilePath);
+            $content = json_decode($content,true);
+            if($content['timestamp'] < $timeStamp){
+                $url = $this->createUrl($objectKey,$expired);
+                $set = [
+                    'url' => $url,
+                    'timestamp' => $timestamp,
+                ];
+                file_put_contents($localFilePath, json_encode($set));
+            }else{
+                $url = $content['url'];
+            }
+        }
+
+        return [true, $url];
+    }
+
+    public function getTemporaryUrl($objectKey, $expired = 3500)
+    {
+        $projectName = env('APP_NAME');
+        $cacheKey = 'oss_url_' . $projectName. '_' . md5($objectKey);
+
+        $url = Cache::remember($cacheKey, $expired - 60, function () use ($objectKey, $expired) {
+            return $this->createUrl($objectKey, $expired);
+        });
+
+        return [true, $url];
+    }
+
+    public function createUrl($objectKey, $expiration = 3600){
+        // 初始化OSS客户端
+        $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
+
+        // 生成临时链接
+        $url = $ossClient->signUrl(
+            $this->bucket,
+            $objectKey,
+            $expiration,
+            'GET' // 可选,指定HTTP方法,默认为 GET
+        );
+
+        return $url;
+    }
+
+    // 阿里云上是否存在图片
+    public function isIsset($objectKey){
+        // 初始化OSS客户端
+        $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
+
+        if ($ossClient->doesObjectExist($this->bucket, $objectKey)) return true;
+
+        return false;
+    }
+}

+ 1 - 0
composer.json

@@ -9,6 +9,7 @@
     "license": "MIT",
     "require": {
         "php": "^7.2.5|^8.0",
+        "aliyuncs/oss-sdk-php": "2.7",
         "fideloper/proxy": "^4.4",
         "firebase/php-jwt": "^6.4",
         "fruitcake/laravel-cors": "^2.2",