8

我想使用 PHP 开发工具包将文件从外部 URL 直接上传到 Amazon S3 存储桶。我设法用以下代码做到了这一点:

$s3 = new AmazonS3();
$response = $s3->create_object($bucket, $destination, array(
  'fileUpload' => $source,
  'length' => remote_filesize($source),
  'contentType' => 'image/jpeg'
)); 

其中函数 remote_filesize 如下:

function remote_filesize($url) {
  ob_start();
  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_HEADER, 1);
  curl_setopt($ch, CURLOPT_NOBODY, 1);
  $ok = curl_exec($ch);
  curl_close($ch);
  $head = ob_get_contents();
  ob_end_clean();
  $regex = '/Content-Length:\s([0-9].+?)\s/';
  $count = preg_match($regex, $head, $matches);
  return isset($matches[1]) ? $matches[1] : "unknown";
}

但是,如果我可以在上传到亚马逊时跳过设置文件大小,那就太好了,因为这样可以节省我去我自己的服务器的时间。但是,如果我删除 $s3->create_object 函数中的“长度”属性设置,我会收到一条错误消息,指出“无法确定流式上传的流大小”。任何想法如何解决这个问题?

4

2 回答 2

3

您可以像这样将文件从 url 直接上传到 Amazon S3(我的示例是关于 jpg 图片):

1.将url中的内容转换成二进制

$binary = file_get_contents('http://the_url_of_my_image.....');

2. 创建一个带有主体的 S3 对象以将二进制文件传递到

$s3 = new AmazonS3();
$response = $s3->create_object($bucket, $filename, array(
    'body' => $binary, // put the binary in the body
    'contentType' => 'image/jpeg'
));

仅此而已,而且速度非常快。享受!

于 2013-01-18T23:23:59.430 回答
0

您对远程服务器/主机有任何控制权吗?如果是这样,您可以设置一个 php 服务器来在本地查询文件并将数据传递给您。

如果没有,您可以使用 curl 之类的东西来检查标题;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://sstatic.net/so/img/logo.png');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$size = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
var_dump($size);

这样,您使用的是 HEAD 请求,而不是下载整个文件——仍然,您依赖于远程服务器发送正确的 Content-length 标头。

于 2012-05-25T10:15:01.660 回答