我想使用 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";
}
但是,如果我可以在上传到 Amazon 时跳过设置文件大小,那就太好了,因为这样可以节省我访问自己服务器的时间。但是,如果我删除 $s3->create_object 函数中的“长度”属性设置,我会收到一条错误消息,指出“无法确定流式上传的流大小。”有什么想法可以解决这个问题吗?
最佳答案
你可以像这样从 url 直接上传文件到 Amazon S3(我的例子是关于一张 jpg 图片):
<强>1。将url中的内容二进制转换
$binary = file_get_contents('http://the_url_of_my_image.....');
<强>2。创建一个带有 body 的 S3 对象以将二进制文件传递到
$s3 = new AmazonS3();
$response = $s3->create_object($bucket, $filename, array(
'body' => $binary, // put the binary in the body
'contentType' => 'image/jpeg'
));
仅此而已,而且速度非常快。享受吧!
关于php - 使用 PHP SDK 将外部文件上传到 AWS S3 存储桶,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10698170/