1. 程式人生 > 實用技巧 >PHP上傳檔案到阿里雲OSS,nginx代理訪問

PHP上傳檔案到阿里雲OSS,nginx代理訪問

1. 阿里雲OSS建立儲存空間Bucket(讀寫許可權為:公共讀)

2. 拿到相關配置

accessKeyId:*********
accessKeySecret:*********
endpoint:********
bucket:********

3.建立 oss.php上傳類 (基於thinkphp5)

<?php
namespace app\controller;
use OSS\OssClient;
class Oss {
    private static $_instance;

    private function __construct() {
    }

    private function __clone() {
    }
    /**
     * 獲取一個OssClient例項
     * @return null|OssClient
     */
    public static function getInstance() {
        if (!(self::$_instance instanceof OssClient)) {
            try {
                self::$_instance = new OssClient(env(‘oss.access_key_id‘), env(‘oss.access_key_secret‘), env(‘oss.endpoint‘), false);
            } catch (OssException $e) {
                printf(__FUNCTION__ . "creating OssClient instance: FAILED\n");
                printf($e->getMessage() . "\n");
                return null;
            }
        }
        return self::$_instance;
    }
    /**
     * 獲取bucket
     * @return string
     */
    public static function getBucketName()
    {
        return env(‘oss.bucket‘);
    }
}

廣州vi設計公司http://www.maiqicn.com 辦公資源網站大全 https://www.wode007.com

3.上傳呼叫

   use app\controller\Oss;
  public function addShopImg(){
        $this->checkParams(‘shop_id‘);
        $file = $this->request->file(‘image‘);
        if ($file && ($file->getError() == ‘‘) && $file->checkImg() && $file->checkSize(5*1024*1024)) {
            $info = $file->move(APP_PATH . ‘../public/upload/shops/‘);
            //上傳圖片至阿里雲oss
            $fileName = ‘biz_oss/upload/shops/‘ . $info->getFilename();
            $ossClient = Oss::getInstance();
            $bucket = Oss::getBucketName();
            $ossClient->uploadFile($bucket, $fileName, $info->getPathname());

            $data[‘shop_img‘] = ‘/upload/shops/‘.$info->getFilename();
            $data[‘shop_id‘] = $this->params[‘shop_id‘];
            $re = db(‘shopImg‘)->insert($data);
            if($re){
                Api::output();
            }else{
                Api::fail(2, ‘上傳失敗‘);
            }
        } else {
            Api::fail(1, ‘圖片不合規‘);
        }
    }

4.訪問 oss域名地址 不可在瀏覽器直接訪問 可用nginx 代理

配置中加入:

location ^~ /biz_oss {
  proxy_pass http://xxxxxx.oss-cn-shenzhen-internal.aliyuncs.com;
}

重啟nginx

nginx配置的域名(server_name)後接上 /biz_oss 如:kwdst.3ce.com/biz_oss 即可指向oss上資源儲存的空間

如下 $oss_url =kwdst.3ce.com/biz_oss

<div>
    <img src="{$oss_url}{$img.shop_img}"  />
</div
>

如此瀏覽器中html即可訪問載入 oss上圖片資源。