3

我一直试图弄清楚如何使用新的 PHP 2.0 SDK 将图像推送到 S3 存储桶。我找到的只是有关如何从您的网络服务器而不是从本地计算机上传图像的教程。这是我正在使用的代码

$result = $s3->putObject(array(
    'Bucket' => $bucketname,
    'Key'    => $filename,
    'SourceFile' => $path,
    'ACL'    => 'public-read',
    'ContentType' => 'image/jpeg',
    'StorageClass' => 'STANDARD'
));

$filename只是我希望出现在存储桶中的文件名,并且$path是我计算机上文件的本地路径。这会将一个文件放到存储桶上,但是当我尝试打开图像时,它只是显示为一个没有图像缩略图的空屏幕。我检查了一下,它似乎只上传了 30 个字节。有人可以指出我正确的方向吗?

4

2 回答 2

2

因此,为了上传,您还需要指定 Body。因此,如果您从计算机上传,这将是代码

$s3 = $aws->get('s3');
$filename = $_FILES['file']['name'];
$tmpFile = $_FILES['file']['tmp_name'];
$imageType = $_FILES['file']['type'];
// Upload a publicly accessible file.
// The file size, file type, and MD5 hash are automatically calculated by the SDK
try {
    $s3->putObject(array(
        'Bucket' => $bucketname,
        'Key' => $filename,
        'Body'   => fopen($tmpFile, 'r'),
        'ACL' => 'public-read',
        'ContentType' => $imageType,
        'StorageClass' => 'STANDARD'
    ));
} catch (S3Exception $e) {
    echo "There was an error uploading the file.\n";
}

其中 $tmpFile 是您计算机上文件的路径。我正在使用上传机制,因此为什么我使用 temp. 但你可以只放静态路径。

于 2014-01-09T21:33:59.200 回答
0

I had the same problem and Shahin's answer is correct, you can set 'Body' => fopen($tmpFile, 'r'),

However when I did this on my WAMP localhost, I got the error

Warning: fopen(C:\Windows\Temp\phpBDF3.tmp): failed to open stream: No such file or directory

This seems to be a windows permissions issue, and you can resolve it by copying the windows temp file to another temp file in a directory where there are no permissions problems (eg web root):

// $tmpFile was 'C:\Windows\Temp\php8A16.tmp';
// create a new temp file in webroot, and copy the windows tempfile there
$new_temp_location = tmpfile();
$new_temp_location = basename($tmpFile);
copy($tmpFile, $new_temp_location);

// now put the file in the bucket
try {
    $s3->putObject(array(
        'Bucket' => $bucketname,
        'Key' => $filename,
        'Body'   => fopen($new_temp_location, 'r'),
        'ACL' => 'public-read',
        'ContentType' => $imageType,
        'StorageClass' => 'STANDARD'
    ));
} catch (S3Exception $e) {
    echo "There was an error uploading the file.\n";
}

It worked for me - hope it saves someone else some time...

EDIT:

Or slightly simpler, you can use

'SourceFile'   => $new_temp_location,

Instead of

'Body'   => fopen($new_temp_location, 'r'),
于 2014-08-22T09:39:35.307 回答