需求描述

  1. 将静态资源(图片、pdf等)存储到阿里云OSS而不是服务器;
  2. 能够实现私有文件签名访问;
  3. 需要能够动态裁剪图片的大小;

实现方法

  1. 安装扩展
$ composer require "iidestiny/laravel-filesystem-oss" -vvv
  1. 配置文件系统
<?php

return [
   'disks' => [
        //...
        'oss' => [
            'driver' => 'oss',
            'access_key' => env('OSS_ACCESS_KEY'),
            'secret_key' => env('OSS_SECRET_KEY'),
            'endpoint'   => env('OSS_ENDPOINT'),
            'bucket'     => env('OSS_BUCKET'),
            'isCName'    => env('OSS_IS_CNAME', false), // // 如果 isCname 为 false,endpoint 应配置 oss 提供的域名如:`oss-cn-beijing.aliyuncs.com`,否则为自定义域名,,cname 或 cdn 请自行到阿里 oss 后台配置并绑定 bucket
        ],
        //...
    ]
];

OSS各参数值的获取,自行查看阿里云帮助文档

  1. 创建一个service,用于处理url
<?php
namespace App\Services;

use Config;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;

class UrlService
{
    private $Driver = '';

    public function __construct()
    {
        //先获取配置文件
        $this->Driver = Config::get('filesystems.default') ;
    }

    public function getUrl(?/post/$ossKey, $options=null,$private=false,$timeout = 60)
    {
        if (Str::startsWith(?/post/$ossKey, ['http://', 'https://'])) {
            return ?/post/$ossKey;
        }
        
        if (?/post/$ossKey) {
            if ($this->Drive = 'oss') {
                if(Storage::has(?/post/$ossKey)){
                    if($private){
                        $url =  Storage::signUrl(?/post/$ossKey,$timeout);
                    }else{
                        $url = Storage::url(?/post/$ossKey);
                        //将options中的裁剪参数加入osskey
                        if (isset($options['x-oss-process'])) {
                            $url = $url.'x-oss-process='.$options['x-oss-process'].'&';
                        }
                    }
                }
                
            } else {
               $url =  \Storage::disk('public')->url(?/post/$ossKey);
            }
        } else {
            $url =  ?/post/$ossKey;
        }

        return $url;
    }
}
  1. 在模型中利用访问器处理图片等文件的真实地址
public function getImageAttribute($value)
{
    if (isset($value)) {
        $w = we_config('productImageSize','w');
        $h = we_config('productImageSize','h');
        //定义裁剪缩放尺寸,用单色填充
        $options = array('x-oss-process' => "image/resize,m_pad,h_".$h.",w_".$w );
        return (new UrlService)->getUrl($value, $options,true);
    }else{
        return null;
    }
}

总结

重点是使用合适的oss扩展,然后就是写一个UrlService方便调用,最后是laravel模型访问器的使用

Last modification:March 21st, 2019 at 11:07 am