繁体   English   中英

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

[英]Upload external file to AWS S3 bucket using PHP SDK

我想使用PHP SDK将外部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函数中设置'length'属性,我会收到一条错误消息,指出'无法确定流上传的流大小'。 任何想法如何解决这个问题?

您可以将文件从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'
));

这就是全部而且非常快。 请享用!

你对远程服务器/主机有什么控制权吗? 如果是这样,你可以设置一个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头。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM