简体   繁体   English

如何在php中从s3下载文件?

[英]How can I download file from s3 in php?

How can I download file from s3 in php. 如何从s3中的php下载文件。 The following code not working for me... Here is my code 以下代码对我不起作用...这是我的代码

upload file should work correct 上传文件应该可以正常工作

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

download gives me error 下载给我错误

  $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;

error 错误

 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

Simple way to do this: 执行此操作的简单方法:

include Amazon S3 PHP Class in you're project. 在您的项目中包括Amazon S3 PHP Class

instantiate the class: 实例化该类:

1. OO method (e,g; $s3->getObject(...)): 1. OO方法(例如,$ s3-> getObject(...)):

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

2. Statically (e,g; S3::getObject(...)): 2.静态(例如,S3 :: getObject(...)):

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

Then get Objects: 然后获取对象:

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

Usually, the most efficient way to do this is to save the object to a file or resource 通常,最有效的方法是将对象保存到文件或资源中

<?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类-带示例

S3 Class -Documentation S3类-文档

You can try this : 您可以尝试以下方法:

$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 ();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM