[英]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.