aws 文件公网直接访问

前几天接到一个需求,需要图片上传aws后可以直接公网访问,aws文件上传默认是不能直接访问,需要签名,这就不符合我们的场景,因为另外几个服务不想更新,只想读取图片路径

其实也就是在配置aws储存的时候记得开放公网访问即可

这一步不是我配置的,我们运维负责的,所以我也不知道怎么搞,所以直接在网上拿图吧

记得配置,不配置怎么玩都不行

在这里插入图片描述

在这里插入图片描述

编辑

{
    "Version": "2012-10-17",
    "Id": "S3PolicyId1",
    "Statement": [
        {
            "Sid": "statement1",
            "Effect": "Allow",
            "Principal": {
                "AWS": "*"
            },
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::my-bucket/*"
        }
    ]
}

 

冒犯老哥了:给你打个广告:https://blog.csdn.net/qq_31275085/article/details/113547485

 

下面就是代码了,点简单,看官网的文档就可以:https://docs.aws.amazon.com/zh_cn/sdk-for-php/v3/developer-guide/s3-presigned-url.html

说下环境把我用的php5.6 

aws版本号:

"aliyuncs/oss-sdk-php": "2.3.0",

不要问选低版本,因为php5.6不支持高版本的,这里很坑

<?php
/**
 * Aws文件上传封装
 */

use Aws\S3\S3Client;
use Aws\S3\MultipartUploader;
use Config\Application\AwsImage;


class AwsFile
{
    public $key;
    public $secret;

    /**
     * Aws类初始化
     *
     */
    public function __construct()
    {
        $config = __getEnvConfig(AwsImage::$awsImageConfig);
        $this->key = isset($config['key']) ? $config['key'] : "";//key 
        $this->secret = isset($config['secret']) ? $config['secret'] : "";//secret
        $this->region = isset($config['region']) ? $config['region'] : "";//区域
        $this->version = isset($config['version']) ? $config['version'] : "";//版本号
        $this->endpoint = isset($config['endpoint']) ? $config['endpoint'] : "";//公网访问地址
        $this->bucket = isset($config['bucket']) ? $config['bucket'] : "";//桶
        try {
            $credentials = new Aws\Credentials\Credentials($this->key, $this->secret);
            $this->client = new S3Client([
                'version' => $this->version,
                'region' => $this->region,
                'credentials' => $credentials,
                'endpoint' => $this->endpoint,
                //设置访问权限  公开,不然访问不了
                'ACL'    => 'public-read',
//                'debug'   => true
            ]);
        } catch (Exception $e) {
            $msg = $e->getMessage();
            Log::add(__PUBLIC_ . '|s3ImageConstruct', $msg);
            return false;
        }
        return true;

    }

    /**
     * upload file 基础上传
     * name 文件名
     * fileUrl 文件路径(绝对地址)
     */
    public function uploadFile($file_name, $file_path)
    {
        $key = $file_name;
        $fileUrl = $file_path;
        if (!file_exists($fileUrl)) {
            Log::add(__PUBLIC_ . '|awsUploadFile', "当前目录中,文件" . $fileUrl . "不存在");
        }
        try {
            $result = $this->client->putObject([
                'Bucket' => $this->bucket,
                'Key' => trim($key),
                'Body' => fopen($fileUrl, 'rb'),
                'ACL'    => 'public-read',
            ]);
            $fileUrl = $result->get('ObjectURL');
            return $fileUrl;
        } catch (Exception $e) {
            $msg = $e->getMessage();
            Log::add(__PUBLIC_ . '|awsUploadFile', $msg);
            return false;
        }
    }

    /**
     * 自定义分段上传
     */
    public function multipartUploader($file_name, $file_path)
    {
        $source = $file_path;
        //多部件上传
        $uploader = new MultipartUploader($this->client, $source, [
            //存储桶
            'bucket' => $this->bucket,
            //上传后的新地址
            'key'    => $file_name,
            //设置访问权限  公开,不然访问不了
            'ACL'    => 'public-read',
            //分段上传
            'before_initiate' => function (\Aws\Command $command) {
                // $command 是CreateMultipartUpload操作
                $command['CacheControl'] = 'max-age=3600';
            },
            'before_upload'   => function (\Aws\Command $command) {
                // $command 是一个UploadPart操作
                $command['RequestPayer'] = 'requester';
            },
            'before_complete' => function (\Aws\Command $command) {
                // $command 是一个CompleteMultipartUpload操作
                $command['RequestPayer'] = 'requester';
            },
        ]);
        try {
            $result = $uploader->upload();
            //上传成功--返回上传后的地址
            $resultOne = $this->client->getObjectUrl($this->bucket, $file_name);
            $data = [
                'type' => '1',
                'data' => urldecode($result['ObjectURL']),
                'resultOne' => $resultOne,
            ];
        } catch (Aws\Exception\MultipartUploadException $e) {
            //上传失败--返回错误信息
            $uploader =  new MultipartUploader($this->client, $source, [
                'state' => $e->getState(),
            ]);
            $data = [
                'type' => '0',
                'data' =>  $e->getMessage(),
            ];
        }
        return $data;
    }

    /**
     * s3根据文件名称获取url
     * fileName 文件名称
     * publicPath 证书路径
     * expire 过期时间
     * $result = $this->client->getObjectUrl($this->bucket, $name);//此方法将返回给定存储桶和密钥的未签名 URL。
     */
    public function getFileUrl($fileName, $publicPath, $expire = 1)
    {
        if (empty($this->bucket)) {
            return  "";
        }
        try {
            //创建预签名url
            $cmd = $this->client->getCommand('GetObject', [
                'Bucket' => $this->bucket,
                'Key' => trim($fileName)
            ]);
            $request = $this->client->createPresignedRequest($cmd, '+' . $expire . 'weeks');
            $presignedUrl = (string)$request->getUri();//获取签名对象的 URL
            //检验访问url是否有效
            $array = get_headers($presignedUrl, 1);
            if (preg_match('/200/', $array[0])) {
                Log::add(__PUBLIC_ . '|s3GetFileUrlSuccess', "下载证书文件成功,url:".$presignedUrl."fileName".$fileName);
                return $presignedUrl;
            } else {
                Log::add(__PUBLIC_ . '|s3GetFileUrlError', "下载证书文件失败,url无效");
                return "";
            }
        } catch (Aws\S3\Exception\S3Exception $e) {
            $msg = $e->getMessage();
            Log::add(__PUBLIC_ . '|s3GetFileUrl', $msg);
            return false;
        }
    }

    /**
     * 获取文件名称
     */
    public function getFileName($name)
    {
        $arr = explode('/', $name);
        $last = $arr[count($arr) - 1];
        return $last;
    }

}

 

Guess you like

Origin blog.csdn.net/qq_27229113/article/details/115002354