2015-10-14 132 views
0

如何從php下載s3文件。下面的代碼不是爲我工作... 這裏是我的代碼如何從php下載s3文件?

上傳文件應工作正確

try { 
    $s3->putObject([ 
     'Bucket' => $config['s3']['bucket'],//'eliuserfiles', 
     'Key' => "uploads/{$name}", 
     'Body' => fopen($tmp_name, 'r+'), 
     //'SourceFile' => $pathToFile, 
     'ACL' => 'public-read', 
    ]); 

下載給我的錯誤

$objInfo = $s3->get_object_headers($config['s3']['bucket'], "uploads/{$name}"); 
    $obj = $s3->get_object($config['s3']['bucket'], "uploads/{$name}"); 

    header('Content-type: ' . $objInfo->header['_info']['content_type']); 
    echo $obj->body; 

錯誤

PHP Catchable fatal error: Argument 2 passed to Aws\\AwsClient::getCommand() must be of the type array, string given, called in /php_workspace/s3_php/vendor/aws/aws-sdk-php/src/AwsClient.php on line 167 and defined in /php_workspace/s3_php/vendor/aws/aws-sdk-php/src/AwsClient.php on line 211, referer: http://localhost/upload.php 
+0

這可能是一個版本問題。你正在使用哪個版本的aws? – Jan

+0

「aws/aws-sdk-php」:「^ 3.8」 –

回答

1

簡單的方法:

包括Amazon S3 PHP Class在你的項目。

實例化類:

1. OO方法(E,G; $ S3->的getObject(...)):

$s3 = new S3($awsAccessKey, $awsSecretKey);

2.靜態(例如,克; S3 ::的getObject(...)):

S3::setAuth($awsAccessKey, $awsSecretKey);

然後得到對象:

// Return an entire object buffer: 
    $object = S3::getObject($bucket, $uri)); 
    var_dump($object); 

通常情況下,最有效的方式做到這一點是將對象保存到一個文件或資源

<?php 

    // To save it to a file (unbuffered write stream): 
    if (($object = S3::getObject($bucket, $uri, "/tmp/savefile.txt")) !== false) { 
     print_r($object); 
    } 

    // To write it to a resource (unbuffered write stream): 
    $fp = fopen("/tmp/savefile.txt", "wb"); 
    if (($object = S3::getObject($bucket, $uri, $fp)) !== false) { 
     print_r($object); 
    } 

?> 

S3 Class -With Examples

S3 Class -Documentation

0

您可以試試這個:

$bucket= "bucket-name"; 
$filetodownload = "name-of-the-file"; 
$resultbool = $s3->doesObjectExist ($bucket, $filetodownload); 
if ($resultbool) { 
    $result = $client->getObject ([ 
    'Bucket' => $bucket, 
    'Key' => $filetodownload 
]); 
} 
else 
{ 
    echo "file not found";die; 
} 
header ("Content-Type: {$result['ContentType']}"); 
header ("Content-Disposition: attachment; filename=" . $filetodownload); 
header ('Pragma: public'); 
echo $result ['Body']; 
die();