# OSS

向军大叔每晚八点在 抖音 (opens new window)bilibli (opens new window) 直播

xj-small

使用阿里云 OSS 保存静态文件,可以减少网站服务器压力,并可加快网页显示。阿里云也提供了比较系统的 OSS 学习路径 (opens new window) 便于学习使用。下面向军大叔快速带你使用 OSS。

# 服务配置

首先访问阿里云 OSS 服务 (opens new window),并添加 Bucket。

  • 如果公开访问的网站静态文件可以设置权限为「公共读」

image-20200819180800166

# 程序编码

下面来安装阿里云提供的PHP SDK (opens new window)快速将 OSS 功能集成到你的项目中

composer require aliyuncs/oss-sdk-php

下面是使用 OSS 上传文件的代码

use OSS\OssClient;

public function oss(UploadedFile $file)
{
		//文件名
    $object = Auth::id() . '-' . date('Ymdhis') . '.' . $file->extension();
    $ossClient = new OssClient(阿里云accessKeyId, 阿里云accessKeySecret), 阿里云endpoint));
    $info = $ossClient->uploadFile(阿里云bucket, $object, $file->path());
    dd($info);
}

下面是阿里云返回值 ,其中 oss-request-url 字段是文件地址

{
    "server": "AliyunOSS",
    "date": "Sun, 07 Feb 2021 06:56:05 GMT",
    "content-length": "0",
    "connection": "keep-alive",
    "x-oss-request-id": "601F8F05E449963534B9E921",
    "etag": "\"391F8780C5651126B5323F56EAA9FCC1\"",
    "x-oss-hash-crc64ecma": "6403246490882624042",
    "content-md5": "OR+HgMVlESa1Mj9W6qn8wQ==",
    "x-oss-server-time": "43",
    "info": {
        "url": "http://hdcms-test.oss-cn-hangzhou.aliyuncs.com/1-20210207025605.jpg",
        "content_type": null,
        "http_code": 200,
        "header_size": 309,
        "request_size": 410,
        "filetime": -1,
        "ssl_verify_result": 0,
        "redirect_count": 0,
        "total_time": 0.363569,
        "namelookup_time": 0.001116,
        "connect_time": 0.069633,
        "pretransfer_time": 0.069903,
        "size_upload": 135215,
        "size_download": 0,
        "speed_download": 0,
        "speed_upload": 372493,
        "download_content_length": 0,
        "upload_content_length": 135215,
        "starttransfer_time": 0.069907,
        "redirect_time": 0,
        "redirect_url": "",
        "primary_ip": "118.31.219.197",
        "certinfo": [],
        "primary_port": 80,
        "local_ip": "10.0.2.15",
        "local_port": 58712,
        "http_version": 2,
        "protocol": 1,
        "ssl_verifyresult": 0,
        "scheme": "HTTP",
        "appconnect_time_us": 0,
        "connect_time_us": 69633,
        "namelookup_time_us": 1116,
        "pretransfer_time_us": 69903,
        "redirect_time_us": 0,
        "starttransfer_time_us": 69907,
        "total_time_us": 363569,
        "method": "PUT"
    },
    "oss-request-url": "http://hdcms-test.oss-cn-hangzhou.aliyuncs.com/1-20210207025605.jpg",
    "oss-redirects": 0,
    "oss-stringtosign": "PUT\n\nimage/jpeg\nSun, 07 Feb 2021 06:56:05 GMT\n/hdcms-test/1-20210207025605.jpg",
    "oss-requestheaders": {
        "Accept-Encoding": "",
        "Content-Type": "image/jpeg",
        "Date": "Sun, 07 Feb 2021 06:56:05 GMT",
        "Host": "hdcms-test.oss-cn-hangzhou.aliyuncs.com",
        "Authorization": "OSS LTAI4GCfKyV9fyyefBY2npWi:a3CqplRECRSPXiVBdzpDyahvF1A="
    },
    "body": ""
}