首页 PHP 正文
255

AWS-S3 PHP API示例

  • yiqingpeng
  • 2021-03-01
  • 0
  •  
function s3upload($file){
    global $s3, $bucket, $finfo;
    $result = $s3->putObject([
        'Body' => $file->content,
        'Bucket' => $bucket,
        'Key' => "dir/subdir/{$file->name}",
        'ContentType' => $mimeType ? $mimeType : $finfo->buffer($file->content),
        'Metadata' => [
            'fileId' => $file->Id,
            'size' => $file->fileSize,
        ]
    ]);

    return $result;
}

function s3copy($fileName){
    global $s3, $bucket;
    $fromKey = "ab/$fileName";
    $toKey = "cd/$fileName";
    $result = $s3->copy($bucket, $fromKey, $bucket, $toKey);
    return $result;
}

function getFileListOfS3($prefix, $withMeta = false){
    global $s3, $bucket;
    try {
        $result = $s3->listObjects([
            'Bucket' => $bucket,
            'Prefix' => $prefix
        ]);
        $list = (array)$result->get('Contents');
        if ($withMeta) {
            foreach ($list as $key => $item) {
                $list[$key]['Meta'] = getMetaOfS3($item['Key'])->get('Metadata');
            }
        }
        return $list;//return an array, each item contains a key 'Key', value of which is like 'dir1/dir2/sample.jpeg'
    } catch (S3Exception $e) {
        throw new \Exception($e->getMessage());
    }
}

function getMetaOfS3($key){
    global $s3, $bucket;
    try {
        $result = $s3->headObject([
            'Bucket' => $bucket,
            'Key' => $key,
        ]);
        return $result;
    } catch(S3Exception $e) {
        throw new \Exception($e->getMessage());
    }
}

正在加载评论...