xiaogang 4 年 前
コミット
dafc75c0b8
5 ファイル変更257 行追加2 行削除
  1. 34 0
      app/Http/Controllers/Api/UploadController.php
  2. 161 0
      app/Services/OssService.php
  3. 1 0
      composer.json
  4. 53 1
      composer.lock
  5. 8 1
      routes/api.php

+ 34 - 0
app/Http/Controllers/Api/UploadController.php

xqd
@@ -0,0 +1,34 @@
+<?php
+
+
+namespace App\Http\Controllers\Api;
+
+
+use App\Services\OssService;
+use Illuminate\Http\Request;
+
+class UploadController extends Controller
+{
+    public function upload(Request $request)
+    {
+        try {
+            //获取上传的文件
+            $file = $request->file('file');
+            //获取上传图片的临时地址
+            $tmppath = $file->getRealPath();
+            //生成文件名
+            $fileName = rand(1000,9999) . time() .date('ymd') . '.' . $file->getClientOriginalExtension();
+            //拼接上传的文件夹路径(按照日期格式1810/17/xxxx.jpg)
+            $pathName = 'chengluApp/'.date('Y-m/d').'/'.$fileName;
+            //上传图片到阿里云OSS
+            OssService::publicUpload(env('ALI_OSS_BUCKET'), $pathName, $tmppath, ['ContentType' => $file->getClientMimeType()]);
+            //获取上传图片的Url链接
+            $Url = OssService::getPublicObjectURL(env('ALI_OSS_BUCKET'), $pathName);
+        }catch (\Exception $exception){
+            return $this->response->errorForbidden($exception->getMessage());
+        }
+
+        // 返回状态给前端,Laravel框架会将数组转成JSON格式
+        return response()->json(['src' => $Url]);
+    }
+}

+ 161 - 0
app/Services/OssService.php

xqd
@@ -0,0 +1,161 @@
+<?php
+namespace App\Services;
+use Exception;
+use DateTime;
+use JohnLui\AliyunOSS;
+
+class OssService {
+    /* 城市名称:
+     *
+     *  经典网络下可选:杭州、上海、青岛、北京、张家口、深圳、香港、硅谷、弗吉尼亚、新加坡、悉尼、日本、法兰克福、迪拜
+     *  VPC 网络下可选:杭州、上海、青岛、北京、张家口、深圳、硅谷、弗吉尼亚、新加坡、悉尼、日本、法兰克福、迪拜
+     */
+    private $city = '成都';
+    // 经典网络 or VPC
+    private $networkType = '经典网络';
+
+    private $AccessKeyId = "";
+    private $AccessKeySecret = "";
+    private $ossClient;
+    /**
+     * 私有初始化 API,非 API,不用关注
+     * @param boolean 是否使用内网
+     */
+    public function __construct($isInternal = false)
+    {
+        if ($this->networkType == 'VPC' && !$isInternal) {
+            throw new Exception("VPC 网络下不提供外网上传、下载等功能");
+        }
+        $this->ossClient = AliyunOSS::boot(
+            $this->city,
+            $this->networkType,
+            $isInternal,
+            env('ALI_OSS_ACCESS_ID'),
+            env('ALI_OSS_ACCESS_KEY')
+        );
+    }
+    /**
+     * 使用外网上传文件
+     * @param  string bucket名称
+     * @param  string 上传之后的 OSS object 名称
+     * @param  string 上传文件路径
+     * @return boolean 上传是否成功
+     */
+    public static function publicUpload($bucketName, $ossKey, $filePath, $options = [])
+    {
+        $oss = new OSS();
+        $oss->ossClient->setBucket($bucketName);
+        return $oss->ossClient->uploadFile($ossKey, $filePath, $options);
+    }
+    /**
+     * 使用阿里云内网上传文件
+     * @param  string bucket名称
+     * @param  string 上传之后的 OSS object 名称
+     * @param  string 上传文件路径
+     * @return boolean 上传是否成功
+     */
+    public static function privateUpload($bucketName, $ossKey, $filePath, $options = [])
+    {
+        $oss = new OSS(true);
+        $oss->ossClient->setBucket($bucketName);
+        return $oss->ossClient->uploadFile($ossKey, $filePath, $options);
+    }
+    /**
+     * 使用外网直接上传变量内容
+     * @param  string bucket名称
+     * @param  string 上传之后的 OSS object 名称
+     * @param  string 上传的变量
+     * @return boolean 上传是否成功
+     */
+    public static function publicUploadContent($bucketName, $ossKey, $content, $options = [])
+    {
+        $oss = new OSS();
+        $oss->ossClient->setBucket($bucketName);
+        return $oss->ossClient->uploadContent($ossKey, $content, $options);
+    }
+    /**
+     * 使用阿里云内网直接上传变量内容
+     * @param  string bucket名称
+     * @param  string 上传之后的 OSS object 名称
+     * @param  string 上传的变量
+     * @return boolean 上传是否成功
+     */
+    public static function privateUploadContent($bucketName, $ossKey, $content, $options = [])
+    {
+        $oss = new OSS(true);
+        $oss->ossClient->setBucket($bucketName);
+        return $oss->ossClient->uploadContent($ossKey, $content, $options);
+    }
+    /**
+     * 使用外网删除文件
+     * @param  string bucket名称
+     * @param  string 目标 OSS object 名称
+     * @return boolean 删除是否成功
+     */
+    public static function publicDeleteObject($bucketName, $ossKey)
+    {
+        $oss = new OSS();
+        $oss->ossClient->setBucket($bucketName);
+        return $oss->ossClient->deleteObject($bucketName, $ossKey);
+    }
+    /**
+     * 使用阿里云内网删除文件
+     * @param  string bucket名称
+     * @param  string 目标 OSS object 名称
+     * @return boolean 删除是否成功
+     */
+    public static function privateDeleteObject($bucketName, $ossKey)
+    {
+        $oss = new OSS(true);
+        $oss->ossClient->setBucket($bucketName);
+        return $oss->ossClient->deleteObject($bucketName, $ossKey);
+    }
+    /**
+     * -------------------------------------------------
+     *
+     *
+     *  下面不再分公网内网出 API,也不注释了,大家自行体会吧。。。
+     *
+     *
+     * -------------------------------------------------
+     */
+    public function copyObject($sourceBuckt, $sourceKey, $destBucket, $destKey)
+    {
+        $oss = new OSS();
+        return $oss->ossClient->copyObject($sourceBuckt, $sourceKey, $destBucket, $destKey);
+    }
+    public function moveObject($sourceBuckt, $sourceKey, $destBucket, $destKey)
+    {
+        $oss = new OSS();
+        return $oss->ossClient->moveObject($sourceBuckt, $sourceKey, $destBucket, $destKey);
+    }
+    // 获取公开文件的 URL
+    public static function getPublicObjectURL($bucketName, $ossKey)
+    {
+        $oss = new OSS();
+        $oss->ossClient->setBucket($bucketName);
+        return $oss->ossClient->getPublicUrl($ossKey);
+    }
+    // 获取私有文件的URL,并设定过期时间,如 \DateTime('+1 day')
+    public static function getPrivateObjectURLWithExpireTime($bucketName, $ossKey, DateTime $expire_time)
+    {
+        $oss = new OSS();
+        $oss->ossClient->setBucket($bucketName);
+        return $oss->ossClient->getUrl($ossKey, $expire_time);
+    }
+    public static function createBucket($bucketName)
+    {
+        $oss = new OSS();
+        return $oss->ossClient->createBucket($bucketName);
+    }
+    public static function getAllObjectKey($bucketName)
+    {
+        $oss = new OSS();
+        return $oss->ossClient->getAllObjectKey($bucketName);
+    }
+    public static function getObjectMeta($bucketName, $ossKey)
+    {
+        $oss = new OSS();
+        return $oss->ossClient->getObjectMeta($bucketName, $ossKey);
+    }
+}

+ 1 - 0
composer.json

xqd
@@ -12,6 +12,7 @@
         "fideloper/proxy": "^4.4",
         "fruitcake/laravel-cors": "^2.0",
         "guzzlehttp/guzzle": "^7.0.1",
+        "johnlui/aliyun-oss": "~2.0",
         "laravel/framework": "^8.40",
         "laravel/tinker": "^2.5",
         "liyu/dingo-serializer-switch": "^0.3.2",

+ 53 - 1
composer.lock

xqd xqd
@@ -4,7 +4,7 @@
         "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
         "This file is @generated automatically"
     ],
-    "content-hash": "1cedd7f6b4a9a52ab91315cb7a09b0a2",
+    "content-hash": "60023a0be7324c8630c5fe31b8ab6111",
     "packages": [
         {
             "name": "asm89/stack-cors",
@@ -1320,6 +1320,58 @@
             },
             "time": "2021-04-26T09:17:50+00:00"
         },
+        {
+            "name": "johnlui/aliyun-oss",
+            "version": "v2.2.1",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/johnlui/AliyunOSS.git",
+                "reference": "f10fdec4775e22a8295366981e1daf48c62ce5d3"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/johnlui/AliyunOSS/zipball/f10fdec4775e22a8295366981e1daf48c62ce5d3",
+                "reference": "f10fdec4775e22a8295366981e1daf48c62ce5d3",
+                "shasum": "",
+                "mirrors": [
+                    {
+                        "url": "https://mirrors.aliyun.com/composer/dists/%package%/%reference%.%type%",
+                        "preferred": true
+                    }
+                ]
+            },
+            "require": {
+                "php": ">=5.4.0"
+            },
+            "type": "library",
+            "autoload": {
+                "files": [
+                    "src/AliyunOSS.php"
+                ]
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "MIT"
+            ],
+            "authors": [
+                {
+                    "name": "John Lui",
+                    "email": "wenhanlv@gmail.com"
+                }
+            ],
+            "description": "阿里云 OSS 官方 SDK 的 Composer 封装,支持任何 PHP 项目,包括 Laravel、Symfony、TinyLara 等等。",
+            "homepage": "https://github.com/johnlui/AliyunOSS",
+            "keywords": [
+                "AliyunOSS",
+                "aliyun",
+                "oss"
+            ],
+            "support": {
+                "issues": "https://github.com/johnlui/AliyunOSS/issues",
+                "source": "https://github.com/johnlui/AliyunOSS/tree/master"
+            },
+            "time": "2017-04-06T06:48:21+00:00"
+        },
         {
             "name": "laravel/framework",
             "version": "v8.47.0",

+ 8 - 1
routes/api.php

xqd xqd
@@ -77,7 +77,6 @@ $api->version('v1', [
             $api->post('/problem', 'UserController@problem')->name('user.problem');
             $api->post('/looked_me', 'UserController@looked_me')->name('user.looked_me');
             $api->get('/get_vip', 'UserController@get_vip')->name('user.get_vip');
-
         });
 
         /*
@@ -109,6 +108,14 @@ $api->version('v1', [
             $api->post('/get_system_message', 'NoticeController@get_system_message')->name('notice.get_system_message');
         });
 
+
+        /*
+        |--------------------------------------------------------------
+        |  文件上传
+        |--------------------------------------------------------------
+        */
+        $api->post('/upload', 'UploadController@upload')->name('upload');
+
         /*
         |--------------------------------------------------------------
         |  退出登录