簡體   English   中英

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

[英]How do I download a file with php and the Amazon S3 sdk?

我正在嘗試讓我的腳本通過 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/

這兩種方法都適合我。 第一種方式看起來更簡潔。

    $command = $s3->getCommand('GetObject', array(
       'Bucket' => 'bucket_name',
       'Key'    => 'object_name_in_s3'  
       'ResponseContentDisposition' => 'attachment; filename="'.$my_file_name.'"'
    ));

    $signedUrl = $command->createPresignedUrl('+15 minutes');
    echo $signedUrl;
    header('Location: '.$signedUrl);
    die();

或者更冗長但仍然實用的方式。

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

通過在回顯 $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;

對於 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"];

如果您仍在 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 的直接下載鏈接通過其服務器代理下載可能出現的問題的人來說,這是一個解決方案。

我將 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 );

此腳本下載 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/');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM