瀏覽代碼

文件上传优化

黄宗昌 2 年之前
父節點
當前提交
138c2c815b
共有 3 個文件被更改,包括 52 次插入70 次删除
  1. 47 65
      app/Helper/AttachmentHelper.php
  2. 3 3
      app/Http/Controllers/V1/AttachmentController.php
  3. 2 2
      app/Services/Base/ErrorCode.php

+ 47 - 65
app/Helper/AttachmentHelper.php

xqd xqd xqd xqd xqd xqd
@@ -1,37 +1,16 @@
 <?php
-
 namespace App\Helper;
 
-use App\Models\SystemConfig;
 use FFMpeg;
 use Illuminate\Http\Request;
 use Illuminate\Http\UploadedFile;
-use Illuminate\Support\Facades\Storage;
 use OSS\OssClient;
-use PHPUnit\Util\Exception;
 use Symfony\Component\HttpFoundation\File\Exception\FileException;
 use App\Services\Base\ErrorCode;
 use App\Models\BaseAttachment;
 
 trait AttachmentHelper
 {
-
-    public function __construct()
-    {
-        //在 .env 文件里配置下面可测试文件上传OSS
-        //ALI_OSS_ACCESS_ID=LTAI5tHMYxyoEkmGqQZjbpmk
-        //ALI_OSS_ACCESS_KEY=Fqj8J1JH0yyRpLvOjNFj5usjvfvHns
-        //ALI_OSS_BUCKET=zhengda
-        //ALI_OSS_ENDPOINT=oss-cn-chengdu.aliyuncs.com
-
-        $this->fileDriver = env('FILESYSTEM_DRIVER');
-        $this->bucket = env('ALI_OSS_BUCKET');
-        $this->accessId = env('ALI_OSS_ACCESS_ID');
-        $this->accessKey = env('ALI_OSS_ACCESS_KEY');
-        $this->endPoint = env('ALI_OSS_ENDPOINT');
-        $this->ossClient = new OssClient($this->accessId, $this->accessKey, $this->endPoint);
-    }
-
     /**
      * @param Request $request
      * @param $key
@@ -39,10 +18,9 @@ trait AttachmentHelper
      * @param float|int $size
      * @param array $mimeType
      * @return array|mixed
-     * @throws \Exception
+     * @throws \OSS\Core\OssException
      */
-    public function uploadAttachment(Request $request, $key, $tag = 'files', $size = 200 * 1024 * 1024, array $mimeType = [])
-    {
+    public function uploadAttachment(Request $request, $key, $tag = 'files', $size = 200 * 1024 * 1024, array $mimeType = []) {
         if ($request->hasFile($key)) {
             $files = $request->file($key);
             if ($files === null) {
@@ -51,6 +29,7 @@ trait AttachmentHelper
             if ($files instanceof UploadedFile) {
                 $files = [$files];
             }
+
             $result = [];
             foreach ($files as $idx => $file) {
                 if (!$file->isValid()) {
@@ -69,10 +48,11 @@ trait AttachmentHelper
                 }
                 $clientName = $file->getClientOriginalName();
                 $md5 = md5($clientName . time());
-                $md5_filename = $md5 . '.' . $file->getClientOriginalExtension();
+                //因为 $md5 32 位字符太长,创建群聊头像失败
+                $md5_filename = substr($md5, 0, 20) . '.' . $file->getClientOriginalExtension();
                 try {
                     //本地上传
-                    if (env('FILESYSTEM_DRIVER') == 'local') {
+                    if(env('FILESYSTEM_DRIVER')=='local'){
                         $rel_path = '/upload/' . $tag . '/' . date('Ymd');
                         $path = public_path() . $rel_path;
                         if (!file_exists($path)) {
@@ -80,47 +60,52 @@ trait AttachmentHelper
                                 throw new \Exception(trans('api.ATTACHMENT_MAKE_FOLDER_ERROR'));
                             }
                         }
+
                         $file->move($path, $md5_filename);
-                        $realPath = $path . '/' . $md5_filename;
-                        $urlPath = $rel_path . '/' . $md5_filename;
+
+                        $real_path = $path . '/' . $md5_filename;
+                        $url_path = $rel_path . '/' . $md5_filename;
+
                         if ($fileMimeType == "video/mp4" || $fileMimeType == "video/quicktime") {
                             $ffmpeg = FFMpeg\FFMpeg::create(array(
-                                'ffmpeg.binaries' => '/usr/bin/ffmpeg',
+                                'ffmpeg.binaries'  => '/usr/bin/ffmpeg',
                                 'ffprobe.binaries' => '/usr/bin/ffprobe'
                             ));
-                            $video = $ffmpeg->open($realPath);
+                            $video = $ffmpeg->open($real_path);
                             $vpath = public_path() . '/upload/vpic/';
                             if (!file_exists($vpath)) {
                                 if (!@mkdir($vpath, 0755, true)) {
                                     return trans('api.ATTACHMENT_MAKE_FOLDER_ERROR');
                                 }
                             }
-                            $pic = $vpath . $md5 . '.jpg';
-                            $video->frame(FFMpeg\Coordinate\TimeCode::fromSeconds(1))->save($pic);
+                            $pic = $vpath.$md5.'.jpg';
+                            $video
+                                ->frame(FFMpeg\Coordinate\TimeCode::fromSeconds(1))
+                                ->save( $pic );
                         }
-                        $result[$idx] = 'http://' . $_SERVER['HTTP_HOST'] . $urlPath;
-
-                    } elseif (env('FILESYSTEM_DRIVER') == 'oss') {
-
-                        $tmppath  = $file->getRealPath(); //获取上传图片的临时地址
-                        $fileName = date('YmdHis') .rand(10000, 99999). '.' . $file->getClientOriginalExtension(); //生成文件名
-                        $pathName = $tag . '/' . date('Y-m') . '/' . $fileName;
-                        $upResult = $this->ossClient->uploadFile($this->bucket, $pathName, $tmppath, ['ContentType' => $file->getClientMimeType()]); //上传图片到阿里云OSS
-                        $url = $upResult['info']['url'];
-                        $realPath = $url;
-                        $urlPath  = $url;
+                        $url = $url_path;
+                        $result[$idx] = 'https://'.$_SERVER['HTTP_HOST'].$url_path;
+                    }elseif (env('FILESYSTEM_DRIVER')=='oss'){
+                        //获取上传图片的临时地址
+                        $tmppath = $file->getRealPath();
+                        //生成文件名
+                        $fileName = rand(100, 999) . time() . date('ymd') . '.' . $file->getClientOriginalExtension();
+                        $pathName = 'golf/' . date('Y-m/d') . '/' . $fileName;
+                        //上传图片到阿里云OSS
+                        $oss = new OssClient(env('ALI_OSS_ACCESS_ID'), env('ALI_OSS_ACCESS_KEY'), env('ALI_OSS_ENDPOINT'));
+                        $res = $oss->uploadFile(env('ALI_OSS_BUCKET'), $pathName, $tmppath, ['ContentType' => $file->getClientMimeType()]);
+                        $url = $res['info']['url'];
                         $result[$idx] = $url;
                     }
-                    //将上传的图片存入到数据表作为记录
                     $attachment = new BaseAttachment();
                     $attachment->name = $clientName;
                     $attachment->md5  = $md5;
-                    $attachment->path = $realPath;
-                    $attachment->url  = $urlPath;
+                    $attachment->path = $url;
+                    $attachment->url  = $url;
                     $attachment->size = $fileSize;
                     $attachment->file_type = $fileMimeType;
                     if (!$attachment->save()) {
-                        @unlink($realPath);
+                        @unlink($url);
                         throw new \Exception(trans('api.ATTACHMENT_SAVE_ERROR'));
                     }
                 } catch (FileException $e) {
@@ -134,37 +119,34 @@ trait AttachmentHelper
         } else {
             throw new \Exception(trans('api.ATTACHMENT_UPLOAD_INVALID'));
         }
+
     }
 
     /**
      * 删除附件
      *
-     * @param $picUrl 图片地址
+     * @param $md5 string 删除文件的md5码
      * @return int 错误码or 0(成功)
      */
-    public function deleteAttachment($picUrl)
-    {
-        if ($this->fileDriver == 'local') {
-            $attachment = BaseAttachment::where(['path' => $picUrl])->first();
-            if (!$attachment) {
-                return false;
-            }
-            if (file_exists($attachment->path)) {
-                if (@unlink($attachment->path)) {
-                    if (!$attachment->delete()) {
-                        return false;
-                    }
+    public function deleteAttachment($md5) {
+        $attachment = BaseAttachment::where(['md5' => $md5])->first();
+        if (!$attachment) {
+            return ErrorCode::ATTACHMENT_NOT_EXIST;
+        }
+        if (file_exists($attachment->path)) {
+            if (@unlink($attachment->path)) {
+                if ($attachment->delete()) {
+                    return 0;
                 } else {
-                    return false;
+                    return ErrorCode::ATTACHMENT_RECORD_DELETE_FAILED;
                 }
             } else {
-                return false;
+                return ErrorCode::ATTACHMENT_DELETE_FAILED;
             }
-        } elseif ($this->fileDriver == 'oss') {
-            $this->ossClient->deleteObject($this->bucket, $picUrl);
+        } else {
+            return ErrorCode::ATTACHMENT_NOT_EXIST;
         }
 
-        return true;
     }
 
 }

+ 3 - 3
app/Http/Controllers/V1/AttachmentController.php

xqd xqd xqd
@@ -3,7 +3,7 @@
 namespace App\Http\Controllers\V1;
 
 use Illuminate\Http\Request;
-//use App\Helper\AttachmentHelper;
+use App\Helper\AttachmentHelper;
 use App\Services\Base\ErrorCode;
 use App\Services\AttachmentServer;
 use Illuminate\Support\Facades\Validator;
@@ -11,7 +11,7 @@ use Illuminate\Support\Facades\Validator;
 
 class AttachmentController extends Controller
 {
-    //use AttachmentHelper;
+    use AttachmentHelper;
 
     /**
      * * 可能出现的错误代码:
@@ -46,7 +46,7 @@ class AttachmentController extends Controller
             if ($validator->fails()) {
                 throw new \Exception($validator->messages()->first());
             }
-            $result = (new AttachmentServer())->uploadAttachment($request, $request->post('file'), $request->post('tag'), 10 * 1024 * 1024, [
+            $result = $this->uploadAttachment($request, $request->input('file'), $request->input('tag'), 10 * 1024 * 1024, [
                 'image/jpeg',
                 'image/png',
                 'image/gif',

+ 2 - 2
app/Services/Base/ErrorCode.php

xqd xqd
@@ -27,7 +27,7 @@ final class ErrorCode
      * 通用常量
      */
     const NOT_LOGIN = 100;
-    const NOT_ALLOW = 112;  
+    const NOT_ALLOW = 112;
     const PARAMS_ERROR = 101;
     const REGISTER_FALSE = 102;
     const REGISTER_CONFIRM_FALSE = 103;
@@ -88,7 +88,7 @@ final class ErrorCode
     //const CASH_MONEY_NO_ENOUGH = 905;
     //const CASH_MONEY_MAX = 906;
 
-    // const ATTACHMENT_NOT_EXIST = 1203;
+     const ATTACHMENT_NOT_EXIST = 1203;
     // const ATTACHMENT_MIME_NOT_ALLOWED = 1202;
     // const MERCHANT_CREDIT_NOT_ENOUGH = 1304;
     // const MEMBER_CREDIT_NOT_ENOUGH = 1305;