0
点赞
收藏
分享

微信扫一扫

上传日志到aws日志服务

无聊到学习 03-23 22:00 阅读 2
1.下载composer插件

 2.编辑配置文件config/filesystem.php

'disks' => [
    // ...
    's3' => [
        'driver' => 's3',
        'key' => env('AWS_ACCESS_KEY_ID'),
        'secret' => env('AWS_SECRET_ACCESS_KEY'),
        'region' => env('AWS_DEFAULT_REGION'),//服务点
        'bucket' => env('AWS_BUCKET'),//存储桶桶名
        'url' => env('AWS_URL'), // 如果不是默认的 S3 URL,可以指定
    ],
    // ...
],

3.控制器代码

<?php

namespace App\Http\Controllers;

use Aws\S3\Exception\S3Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Aws\S3\S3Client;

class S3Controller extends Controller
{
    public function upload($file_path=null,$file_local_path=null)
    {
        // 确保文件存在且可读
        if (!file_exists($file_local_path) || !is_readable($file_local_path)) {
            return ['code'=>0,'error' => 'File not found or not readable'];
        }

        $s3 = new S3Client([
            'version' => 'latest',
            'region' => env('AWS_DEFAULT_REGION'),
            'credentials' => [
                 'key' => env('AWS_ACCESS_KEY_ID'),
                'secret' => env('AWS_SECRET_ACCESS_KEY'),
            ],
//            'endpoint' => env('AWS_S3_ENDPOINT'),
//            'debug'=>true,
        ]);

         //判断对象是否存在,这里是判断桶名是否存在
        if (!$s3->doesBucketExist(env('AWS_BUCKET'))) {

            try{
                $s3->createBucket([
                    'Bucket' => env('AWS_BUCKET'),
                ]);
                $s3->waitUntil('BucketExists', ['Bucket' => env('AWS_BUCKET')]);
            } catch (S3Exception $e) {
                return [
                    'code'=>-5,
                    'Bucket Creation Failed' => $e->getMessage()
                ];
            }
        }

        try {
            //上传部分
            $result = $s3->putObject([
                'Bucket' => env('AWS_BUCKET'),
                'Key'    => $file_path,//example  test/123.jpg
                'Body'   => fopen($file_local_path, 'rb'),//file_get_contents($file_local),// ,
                'ACL'    => 'public-read',
                'ContentType' => 'image/jpg',//声明文件上传类型
            ]);

            if ($result['@metadata']['statusCode'] === 200) {

                echo '上传成功';
               

            } else {
                throw new \Exception("上传失败!");
            }

        } catch (S3Exception $e) {
            return [
                'code'=>-1,
                'Upload Failed' => $e->getMessage()
            ];
        }


    }
}
举报

相关推荐

0 条评论