如何使用php和Amazon S3 sdk下载文件?

时间:2011-09-12 14:22:55

标签: php amazon-s3

我正在努力使我的脚本通过php在Amazon S3存储桶中显示test.jpg。 这是我到目前为止所做的:

require_once('library/AWS/sdk.class.php');

$s3 = new AmazonS3($key, $secret);

$objInfo = $s3->get_object_headers('my_bucket', 'test.jpg');
$obj = $s3->get_object('my_bucket', 'test.jpg', array('headers' => array('content-disposition' => $objInfo->header['_info']['content_type'])));

echo $obj->body;

这只是转储页面上的文件数据。我想我还需要发送content-disposition头文件,我认为这是在get_object()方法中完成的,但事实并非如此。

注意:我正在使用此处提供的SDK:http://aws.amazon.com/sdkforphp/

6 个答案:

答案 0 :(得分:17)

这两种方法对我都有用。第一种方式似乎更简洁。

    $object = $s3->getObject(array(
    'Bucket' => 'bucket_name',
    'Key'    => 'object_name_in_s3'   
    ));

    header('Content-Description: File Transfer');
    //this assumes content type is set when uploading the file.
    header('Content-Type: ' . $object->ContentType);
    header('Content-Disposition: attachment; filename=' . $my_file_name);
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');

    //send file to browser for download. 
    echo $object->body;

或者更罗嗦但仍然有效的方式。

        ArrayList<ArrayList<String>> module_list = new ArrayList<ArrayList<String>>();
    ArrayList<String> new_row = new ArrayList<String>();

    new_row.add(module_description,"Description0");
    new_row.add(module_address, "Address0");
    new_row.add(module_type, "Type0");
    module_list.add(0,new_row);

    new_row.add(module_description, "Description1");
    new_row.add(module_address,"Address1");
    new_row.add(module_type, "Type1");
    module_list.add(1,new_row);

    new_row.add(module_description, "Description2");
    new_row.add(module_address, "Address2");
    new_row.add(module_type,"Type2");;
    module_list.add(2, new_row);


    for(int row = 0; row<module_list.size() ; row++) {
        ArrayList<String> returned_row = new ArrayList<String>();
        returned_row = module_list.get(row);

        Log.d("APP", "Row: "+ Integer.toString(row));
        Log.d("APP", "Module description: " + returned_row.get(module_description));
        Log.d("APP", "Module address: " + returned_row.get(module_address));
        Log.d("APP", "Module type: " + returned_row.get(module_type));
    }

答案 1 :(得分:13)

通过在回显$ object体之前回显出内容类型的标题来实现它。

$objInfo = $s3->get_object_headers('my_bucket', 'test.jpg');
$obj = $s3->get_object('my_bucket', 'test.jpg');

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

答案 2 :(得分:3)

对于PHP sdk3,更改Maximus的最后一行答案

    $object = $s3->getObject(array(
       'Bucket' => 'bucket_name',
       'Key'    => 'object_name_in_s3'   
    ));

    header('Content-Description: File Transfer');
    //this assumes content type is set when uploading the file.
    header('Content-Type: ' . $object->ContentType);
    header('Content-Disposition: attachment; filename=' . $my_file_name);
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');

    //send file to browser for download. 
    echo $object["Body"];

答案 3 :(得分:1)

我将Content-Disposition标头添加到getAuthenticatedUrl();

 // Example
 $timeOut = 3600; // in seconds
 $videoName = "whateveryoulike";
 $headers = array("response-content-disposition"=>"attachment");
 $downloadURL = $s3->getAuthenticatedUrl( FBM_S3_BUCKET, $videoName, FBM_S3_LIFETIME + $timeOut, true, true, $headers );

答案 4 :(得分:0)

如果您仍在寻找2019年以上的相关问题的答案,请使用适用于PHP 3.x的AWS开发工具包,尤其是composer的“ 2006-03-01”,以下内容对我有用


...

/**
 * Download a file
 * 
 * @param   string  $object_key
 * @param   string  $file_name
 * @return  void
 */
function download($object_key, $file_name = '') {
  if ( empty($file_name) ) {
    $file_name = basename($file_path);
  }
  $cmd = $s3->getCommand('GetObject', [
    'Bucket'                        => '<aws bucket name>',
    'Key'                           => $object_key,
    'ResponseContentDisposition'    => "attachment; filename=\"{$file_name}\"",
  ]);
  $signed_url = $s3->createPresignedRequest($cmd, '+15 minutes') // \GuzzleHttp\Psr7\Request
                ->getUri() // \GuzzleHttp\Psr7\Uri
                ->__toString();
  header("Location: {$signed_url}");
}
download('<object key here>', '<file name for download>');

注意:这是一种解决方案,适用于那些希望避免使用来自AWS的直接下载链接通过其服务器代理下载而引起的问题。

答案 5 :(得分:0)

此脚本下载S3服务上所有目录中的所有文件,例如Amazon S3或DigitalOcean空间。

  1. 配置您的凭据(请参阅类常量和该类下的代码)
  2. 运行composer require aws/aws-sdk-php
  3. 假设您已将此脚本保存到index.php,然后在控制台中运行php index.php并使其撕裂!

请注意,我只是写了代码来完成工作,所以我可以关闭我的DO帐户。它可以满足我的需要,但是我可以做一些改进以使其更可扩展。享受吧!


<?php

require 'vendor/autoload.php';
use Aws\S3\S3Client;

class DOSpaces {

    // Find them at https://cloud.digitalocean.com/account/api/tokens
    const CREDENTIALS_API_KEY           = '';
    const CREDENTIALS_API_KEY_SECRET    = '';

    const CREDENTIALS_ENDPOINT          = 'https://nyc3.digitaloceanspaces.com';
    const CREDENTIALS_REGION            = 'us-east-1';
    const CREDENTIALS_BUCKET            = 'my-bucket-name';

    private $client = null;

    public function __construct(array $args = []) {

        $config = array_merge([
            'version' => 'latest',
            'region'  => static::CREDENTIALS_REGION,
            'endpoint' => static::CREDENTIALS_ENDPOINT,
            'credentials' => [
                'key'    => static::CREDENTIALS_API_KEY,
                'secret' => static::CREDENTIALS_API_KEY_SECRET,
            ],
        ], $args);

        $this->client = new S3Client($config);
    }

    public function download($destinationRoot) {
        $objects = $this->client->listObjectsV2([
            'Bucket' => static::CREDENTIALS_BUCKET,
        ]);

        foreach ($objects['Contents'] as $obj){

            echo "DOWNLOADING " . $obj['Key'] . "\n";
            $result = $this->client->getObject([
                'Bucket' => 'dragon-cloud-assets',
                'Key' => $obj['Key'],
            ]);

            $this->handleObject($destinationRoot . $obj['Key'], $result['Body']);

        }
    }

    private function handleObject($name, $data) {
        $this->ensureDirExists($name);

        if (substr($name, -1, 1) !== '/') {
            echo "CREATING " . $name . "\n";
            file_put_contents($name, $data);
        }
    }

    private function ensureDirExists($name) {
        $dir = $name;
        if (substr($name, -1, 1) !== '/') {
            $parts = explode('/', $name);
            array_pop($parts);
            $dir = implode('/', $parts);
        }

        @mkdir($dir, 0777, true);
    }

}

$doSpaces = new DOSpaces([
    'endpoint' => 'https://nyc2.digitaloceanspaces.com',
    'credentials' => [
        'key'    => '12345',
        'secret' => '54321',
    ],
]);
$doSpaces->download('/home/myusername/Downloads/directoryhere/');