我想使用 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";
}
但是,如果我可以在上传到亚马逊时跳过设置文件大小,那就太好了,因为这可以节省我访问自己的服务器的行程。但是,如果我删除在 $s 3->create_object 函数中设置"length"属性,则会收到一条错误消息,指出"无法确定流上传的流大小"。有什么想法可以解决这个问题吗?
您可以像这样将文件从 url 直接上传到 Amazon S3(我的例子是关于 jpg 图片的):
1.将二进制网址中的内容转换为二进制
$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 请求,而不是下载整个文件 - 您仍然依赖于远程服务器发送正确的内容长度标头。