0%

Lumen接入Azure的blob存储配置

[TOC]

最近在做的一个项目使用的是Azure服务器,其中数据库、redis、和对象存储和国内厂商都有不同,最直观的区别就是Azure基本都是SSL方式进行连接,相对国内云服务器厂商的服务接入没有那么无脑,今天简单记录下Azure提供的blob存储在lumen框架的接入

几个轮子

1
2
composer require league/flysystem
composer require league/flysystem-azure-blob-storage

配置

Laravel/Lumen 提供了很强大的文件管理系统和云存储功能的集成

/Users/zhimma/Data/www/lumen/vendor/laravel/lumen-framework/config目录复制一份到项目根目录下,主要检查/Users/zhimma/Data/www/lumen/config/filesystems.php这个文件是否存在

下面进行配置:

  1. /Users/zhimma/Data/www/lumen/config/filesystems.php

    在配置s3下方添加如下内容:

    1
    2
    3
    4
    5
    6
    7
    ...
    'azure' => [
    'driver' => 'azure',
    'name' => env('AZURE_STORAGE_NAME', 'xxx'),
    'key' => env('AZURE_STORAGE_KEY', 'xxx'),
    'container' => env('AZURE_STORAGE_CONTAINER', 'xxx'),
    ],
  2. /Users/zhimma/Data/www/lumen/bootstrap/app.php

    1. 添加$app->configure('filesystems');表示加载该配置文件项
    2. 添加$app->register(\Illuminate\Filesystem\FilesystemServiceProvider::class);加载该服务提供者
  3. /Users/zhimma/Data/www/lumen/app/Providers/AppServiceProvider.php

    新增下面的方法

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    public function boot()
    {
    Storage::extend('azure', function ($app, $config) {
    $endpoint = sprintf('DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s;EndpointSuffix=core.chinacloudapi.cn',
    $config['name'], $config['key'], $config['url'] ?? null, $config['prefix'] ?? null);
    $client = BlobRestProxy::createBlobService($endpoint);
    $adapter = new AzureBlobStorageAdapter($client, $config['container'], $config['prefix'] ?? null);

    return new Filesystem($adapter);
    });
    }

    参考文档:https://learnku.com/docs/laravel/5.5/filesystem/1319#custom-filesystems

上传测试

新增好路由后,我们进行上传测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class UploadController extends Controller
{
/**
* 文件上传
*
* @param Request $request
*
* @return \Illuminate\Http\JsonResponse
* @throws \Exception
* @author zhimma
* @date 2019/5/27 12:00 PM
*/
public function upload(Request $request)
{
if (!$request->hasFile('file')) {
throw new \Exception("文件不存在");
}
$file = $request->file('file');
if (!$file->isValid()) {
throw new \Exception($file->getErrorMessage());
}
$path = Storage::put(date('Ymd'), $file);
$url = env('AZURE_BLOB_URL').'/'.env('AZURE_STORAGE_CONTAINER').'/'.$path;

return $this->success(['url' => $url]);
}
}

返回如下

1
2
3
4
5
6
7
8
{
"status": "success",
"httpCode": 200,
"statusCode": 0,
"data": {
"url": "https://xxx.blob.core.chinacloudapi.cn/xxx/20190816/FKRJQXqo1Rdm77mAW2biuBSaVx12mH4U52NtKlZI.png"
}
}

至此配置完成

参考

https://matthewdaly.co.uk/blog/2016/10/24/creating-an-azure-storage-adapter-for-laravel/

https://stackoverflow.com/questions/56267900/how-to-use-azure-blob-in-lumen