使用PHP SDK将外部文件上载到AWS S3存储桶

Bjo*_*orn 7 php upload amazon-s3

我想使用PHP SDK将外部URL中的文件直接上传到Amazon S3存储桶.我设法使用以下代码执行此操作:

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

函数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";
}
Run Code Online (Sandbox Code Playgroud)

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

小智 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);
Run Code Online (Sandbox Code Playgroud)

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