【问题标题】:Receive image via PHP curl, then upload to S3通过 PHP curl 接收图像,然后上传到 S3
【发布时间】:2016-01-26 15:37:19
【问题描述】:

我正在使用 PHP CURL 从 REST API 生成自定义的 PNG 图像。加载此图像后,我想将其上传到 AWS S3 存储桶并显示指向它的链接。

到目前为止,这是我的脚本:

$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, 'http://url-to-generate-image.com?options=' + $_GET['options']);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
$info=curl_getinfo($ch);
curl_close($ch);

//require S3 Class
if (!class_exists('S3')) {
    require_once('S3.php');
}

//AWS access info
if (!defined('awsAccessKey')) {
    define('awsAccessKey', 'MY_ACCESS_KEY');
}
if (!defined('awsSecretKey')) {
    define('awsSecretKey', 'MY_SECRET_KEY');
}

//instantiate the class
$s3 = new S3(awsAccessKey, awsSecretKey);
$s3->putBucket('bucket-name', S3::ACL_PUBLIC_READ);

$file_name = md5(rand(99,99999999)) + '-myImage.png';

if ($s3->putObjectFile($data, 'bucket-name' , $file_name, S3::ACL_PUBLIC_READ)) {

    echo 'success';

    $gif_url = 'http://bucket-name.s3.amazonaws.com/'.$file_name;

} else {

    echo 'failed';

}

它总是失败。现在,我认为问题在于我在哪里使用putObjectFile - $data 变量代表图像,但也许它必须以另一种方式传递?

我正在为 S3 使用一个通用的 PHP 类:http://undesigned.org.za/2007/10/22/amazon-s3-php-class

【问题讨论】:

  • 对该类的简要介绍让我认为该库期望第一个参数是文件路径,而不是文件数据。如果它不是文件或不可访问,则运行 trigger_error('S3::inputFile(): Unable to open input file: '.$file, E_USER_WARNING); 并返回 false。
  • @JonStirling - 谢谢,你是对的。我一直在谷歌搜索,甚至无法确定是否有办法将文件数据上传到 S3 ..
  • @Mortimer 检查我的答案。
  • 我强烈建议您不要使用该类,因为它在 2011 年太旧了,并且没有更新

标签: php curl amazon-s3


【解决方案1】:

使用PHP内存包装器存储图片内容,使用$s3->putObject()方法:

$fp = fopen('php://memory', 'wb');
fwrite($fp, $data);
rewind($fp);
$s3->putObject([
    'Bucket' => $bucketName,
    'Key' => $fileName,
    'ContentType' => 'image/png',
    'Body' => $fp,
]);
fclose($fp);

经过验证的方法(您可能需要稍微修改代码)使用 PHP 5.5 和最新的 AWS 库。

http://php.net/manual/en/wrappers.php.php

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-31
    • 1970-01-01
    • 2015-06-16
    • 2017-10-16
    • 2015-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多