使用PHP SDK将文件上传到Amazon S3

5

我正在尝试使用Amazon S3的PHP SDK上传图片。因此,我编写了一个小脚本来完成此操作。然而,我的脚本无法正常工作,并且我的异常没有返回任何错误消息。

我是AWS的新手,感谢您的帮助。

以下是代码:

Config.php

<?php 

return array(
'includes' => array('_aws'),
'services' => array(
  'default_settings' => array(
      'params' => array(
          'key'    => 'PUBLICKEY',
          'secret' => 'PRIVATEKEY',
          'region' => 'eu-west-1'
      )
    )
  )
);

?>

Index.php

 <?php


//Installing AWS SDK via phar
require 'aws.phar';

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

$bucket = 'infact';
$keyname = 'myImage';

// $filepath should be absolute path to a file on disk                      
$filepath = 'image.jpg';

// Instantiate the client.
$s3 = S3Client::factory('config.php');

// Upload a file.
try {

$result = $s3->putObject(array(
    'Bucket'       => $bucket,
    'Key'          => $keyname,
    'SourceFile'   => $filePath,
    'ContentType'  => 'text/plain',
    'ACL'          => 'public-read',
    'StorageClass' => 'REDUCED_REDUNDANCY'
));

 // Print the URL to the object.
    echo $result['ObjectURL'] . "\n";
} catch (S3Exception $e) {
    echo $e->getMessage() . "\n";
}

?>

编辑:我现在正在使用这段代码,但它仍然不起作用。我甚至没有错误或异常消息。

    <?php

require 'aws.phar';

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

$bucket = 'infactr';
$keyname = 'sample';
// $filepath should be absolute path to a file on disk                      
$filepath = 'image.jpg';

// Instantiate the client.
$s3 = S3Client::factory(array(
    'key'    => 'key',
    'secret' => 'privatekey',
    'region' => 'eu-west-1'

    ));

try {
    // Upload data.
    $result = $s3->putObject(array(
        'Bucket' => $bucket,
        'Key'    => $keyname,
        'SourceFile'   => $filePath,
        'ACL'    => 'public-read',
        'ContentType' => 'image/jpeg'
    ));

    // Print the URL to the object.
    echo $result['ObjectURL'] . "\n";
} catch (S3Exception $e) {
    echo $e->getMessage() . "\n";
}

?>

1
你是从网络还是命令行运行这个程序的? - Rico
1
尝试从命令行运行以查看错误。 - Rico
我从未使用过任何带有s3的控制台。你是否使用s3tools.org进行连接? - casusbelli
1
是的,不需要使用s3cmd来尝试您的脚本。您只需运行:php <yourscript>.php即可。 - Rico
1
从Linux命令行 - Rico
显示剩余6条评论
5个回答

8

尝试类似这样的代码(来自AWS文档):

<?php

require 'aws.phar';

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

$bucket = '<your bucket name>';
$keyname = 'sample';
// $filepath should be absolute path to a file on disk                      
$filepath = '/path/to/image.jpg';

// Instantiate the client.
$s3 = S3Client::factory(array(
    'key'    => 'your AWS access key',
    'secret' => 'your AWS secret access key'
));

try {
    // Upload data.
    $result = $s3->putObject(array(
        'Bucket' => $bucket,
        'Key'    => $keyname,
        'SourceFile'   => $filepath,
        'ACL'    => 'public-read'
    ));



    // Print the URL to the object.
    echo $result['ObjectURL'] . "\n";
} catch (S3Exception $e) {
    echo $e->getMessage() . "\n";
}

?>

只要您拥有正确的凭据,这对我来说就很好用。请记住,密钥名称是S3中文件的名称,因此如果您希望密钥与文件名称相同,您需要执行以下操作:$keyname = 'image.jpg';。另外,jpg通常不是plain/text文件类型,您可以省略Content-type字段或只需简单指定:image/jpeg

2
对于那些正在寻找最新的可用版本的人,这是我正在使用的版本。
// Instantiate the client.
$s3 = S3Client::factory(array(
    'credentials' => [
        'key'    => $s3Key,
        'secret' => $s3Secret,
        ],
    'region' => 'us-west-2',
    'version' => "2006-03-01"
));

try {
    // Upload data.
    $result = $s3->putObject(array(
        'Bucket' => $s3Bucket,
        'Key'    => $fileId,
        'SourceFile'   => $filepath."/".$fileName
    ));
    return $result['ObjectURL'];
} catch (S3Exception $e) {
    return false;
}

2
$s3 = S3Client::factory('config.php');

应该是

$s3 = S3Client::factory(include 'config.php');

0
另一种解释的方式是通过展示curl以及如何在php中构建它-务实的方法。 请不要因为丑陋的代码而砸我,只是觉得这个例子很容易让人理解如何从PHP或其他语言上传到Azure。
$azure1 ='https://viperprodstorage1.blob.core.windows.net/bucketnameAtAzure/';
$azure3 ='?sr=c&si=bucketnameAtAzure-policy&sig=GJ_verySecretHashFromAzure_aw%3D';
$shellCmd='ls -la '.$outFileName;
$lsOutput=shell_exec($shellCmd);
#print_r($lsOutput);
$exploded=explode(' ', $lsOutput);
#print_r($exploded);
$fileLength=$exploded[7];
$curlAzure1="curl -v -X PUT -T '" . $outFileName . "' -H 'Content-Length: " . $fileLength . "' ";
$buildedCurlForUploading=$curlAzure1."'".$azure1.$outFileName.$azure3."'";
var_dump($buildedCurlForUploading);
shell_exec($buildedCurlForUploading);

这是实际的curl

shell_exec("curl -v -X PUT -T 'fileName' -H 'Content-Length: fileSize' 'https://viperprodstorage1.blob.core.windows.net/bucketnameAtAzure/fileName?sr=c&si=bucketNameAtAzure-policy&sig=GJ_verySecretHashFromAzure_aw%3D'")

0
以下是上传图像/文件到Amazon S3存储桶的代码。
function upload_agreement_data($target_path, $source_path, $file_name, $content_type)
{
    $fileup_flag = false;

    /*------------- call global settings helper function starts ----------------*/
    $bucketName = "pilateslogic";
    //$global_setting_option = '__cloud_front_bucket__';
    //$bucketName = get_global_settings($global_setting_option);
    /*------------- call global settings helper function ends ----------------*/

    if(!$bucketName)
    {
        die("ERROR: Template bucket name not found!");
    }

    // Amazon profile_template template js upload URL
    $target_profile_template_js_url = "/".$bucketName."/".$target_path;

    // Chatching profile_template template js upload URL
    //$source_profile_template_js_url = dirname(dirname(dirname(__FILE__))).$source_path."/".$file_name;

    // file name
    $template_js_file = $file_name;

    $this->s3->setEndpoint("s3-ap-southeast-2.amazonaws.com");
    if($this->s3->putObjectFile($source_path, $target_profile_template_js_url, $template_js_file, S3::ACL_PUBLIC_READ, array(), array("Content-Type" => $content_type)))
    {
        $fileup_flag = true;
    }
    return $fileup_flag;
}

$source_path = $_SERVER['DOCUMENT_ROOT']."/uploads/".$advertiseImage; $file_name = rand(); $content_type = "image/jpeg"; $target_path = "FreeImage"; $this->upload_agreement_data($target_path,$source_path,$file_name,$content_type); - Neeraj Sharma
function getBucketURL($imageType, $uri) { $bucket = "pilateslogic"; $newUri = $imageType."/".$uri; $fileURL = $this->s3->getAuthenticatedURL($bucket, $newUri, 1000, $hostBucket = false, $https = false); return $fileURL; } - Neeraj Sharma

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接