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

标签 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'
)); 

其中函数 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/

相关文章:

php - JSON 字段中的类似 MySql 的查询

php - 使用 COALESCE 返回带有导航数组页面信息的 META 标题值

php - 按多列对 sql 结果排序时出现问题

PHP上传多个文件只上传1个文件

python - 我可以从 aws s3 恢复下载吗?

python - 如何使用 boto3 在 Python 中获取 S3 目录作为 os.path?

amazon-web-services - 在计费 panic 中锁定公共(public)站点访问

php - Laravel isEmpty 不起作用

rest - 如何使用 Yii2 UploadedFile 类接收带有图像的 POST 请求

ajax - 使用隐藏的ajax上传文件时如何检测iframe接收响应