PHP AWS S3上传文件

PHP AWS S3上传文件

function fileUpload($file,$s3Key,$s3Secret,$ENDPOINT,$bucket){
    require_once 'ThinkPHP/Library/Vendor/Aws/vendor/autoload.php';   //引入类 

    //设置超时
    set_time_limit(0);
    //证书 AWS access KEY ID  和  AWS secret  access KEY 替换成自己的
    //$credentials = new \Aws\Credentials\Credentials('GKI4XZE9MOUO1FFFL2YQ', 'p57mZbR8NZQ9nKBsUbviMrmBEpzTlPNxMWJgNg10');
    $credentials = new \Aws\Credentials\Credentials($s3Key, $s3Secret);

    // $ENDPOINT = "http://192.168.1.230:80/";   
    // define('AWS_KEY', 'GKI4XZE9MOUO1FFFL2YQ');
    // define('AWS_SECRET_KEY', 'p57mZbR8NZQ9nKBsUbviMrmBEpzTlPNxMWJgNg10');
    //s3客户端      
    $s3 =new \Aws\S3\S3Client([
        'region' => '',
        'version' => '2006-03-01',
        'endpoint' => $ENDPOINT,
        'credentials' => [
            'key' => $s3Key,
            'secret' => $s3Secret
        ],
        // Set the S3 class to use objects.dreamhost.com/bucket
        // instead of bucket.objects.dreamhost.com
        'use_path_style_endpoint' => true
    ]);

    //存储桶 获取AWS存储桶的名称
    $bucket = $bucket;//'AWS存储桶名称';
    //需要上传的文件 
    $source = $_SERVER['DOCUMENT_ROOT']."/evercases/Export/".$file; //ROOT_PATH项目根目录,文件的本地路径例:D:/www/abc.jpg;
   // $filesize = filesize($_SERVER['DOCUMENT_ROOT']."/evercases/Export/".$file);
    $filemd5 = md5_file($_SERVER['DOCUMENT_ROOT']."/evercases/Export/".$file);
   // print_r($filemd5);exit;
    //多部件上传
    $uploader = new \Aws\S3\MultipartUploader($s3, $source, [
        //存储桶
        'bucket' => $bucket,
        //上传后的新地址
        'key'    => $filemd5,
        //设置访问权限  公开,不然访问不了
        'ACL'    => 'public-read',
        //分段上传
        'before_initiate' => function (\Aws\Command $command) {
            // $command is a CreateMultipartUpload operation
            $command['CacheControl'] = 'max-age=3600';
        },
        'before_upload'   => function (\Aws\Command $command) {
            // $command is an UploadPart operation
            $command['RequestPayer'] = 'requester';
        },
        'before_complete' => function (\Aws\Command $command) {
            // $command is a CompleteMultipartUpload operation
           $command['RequestPayer'] = 'requester';
        },
    ]);

    try {
            $result = $uploader->upload();
            //上传成功--返回上传后的地址
            $data = [
                'type' => '1',
                'data' => urldecode($result['ObjectURL'])
            ];
    } catch (Aws\Exception\MultipartUploadException $e) {
       //上传失败--返回错误信息
            $uploader =  new \Aws\S3\MultipartUploader($s3, $source, [
                'state' => $e->getState(),
            ]);
             $data = [
                    'type' => '0',
                    'data' =>  $e->getMessage(),
               ];
    } 
    return $data;
}

你可能感兴趣的:(PHP AWS S3上传文件)