2013-10-15 25 views
6

当我想要将图片上传到我的亚马逊S3存储桶时出现问题。
亚马逊S3 - 您的建议上传量小于允许的最小尺寸

我试图上传一个大小为238 KB的jpg图像。我在代码中加入了一个try/catch来检查错误是什么。我总是得到这个错误:

Your proposed upload is smaller than the minimum allowed size

我也试过这与图像从1MB和2MB,同样的错误...。

这里是我的代码:(我已经改变了水桶,按键和图像链接)

<?php 

// Include the SDK using the Composer autoloader 
require 'AWSSDKforPHP/aws.phar'; 

use Aws\S3\S3Client; 
use Aws\Common\Enum\Size; 

$bucket = 'mybucketname'; 
$keyname = 'images'; 
$filename = 'thelinktomyimage'; 

// Instantiate the S3 client with your AWS credentials and desired AWS region 
$client = S3Client::factory(array(
    'key' => 'key', 
    'secret' => 'secretkey', 
)); 


// Create a new multipart upload and get the upload ID. 
$response = $client->createMultipartUpload(array(
    'Bucket' => $bucket, 
    'Key' => $keyname 
)); 

$uploadId = $response['UploadId']; 

// 3. Upload the file in parts. 
$file = fopen($filename, 'r'); 
$parts = array(); 
$partNumber = 1; 
while (!feof($file)) { 
    $result = $client->uploadPart(array(
     'Bucket'  => $bucket, 
     'Key'  => $keyname, 
     'UploadId' => $uploadId, 
     'PartNumber' => $partNumber, 
     'Body'  => fread($file, 5 * 1024 * 1024), 
    )); 
    $parts[] = array(
     'PartNumber' => $partNumber++, 
     'ETag'  => $result['ETag'], 
    ); 

} 

// Complete multipart upload. 
try{ 
    $result = $client->completeMultipartUpload(array(
     'Bucket' => $bucket, 
     'Key'  => $keyname, 
     'UploadId' => $uploadId, 
     'Parts' => $parts, 
    )); 
    $url = $result['Location']; 

    fclose($file); 
} 
catch(Exception $e){ 
    var_dump($e->getMessage()); 
} 


有没有人有这个?在互联网上搜索并没有多大帮助。
也搜索以更改最小上传大小没有提供太多帮助。

UPDATE
当我试图与本地图像(变更的文件名),它的工作!我如何使用联机图像进行此项工作?现在我将它保存在临时文件中,然后从那里上传。但是没有一种方法可以直接存储它,而不需要在本地保存它?

回答

11

最小分段上传大小为5mb(1)。您可能想要使用“正常”上传,而不是分段上传。

(1)http://docs.aws.amazon.com/AmazonS3/latest/API/mpUploadUploadPart.html

+3

的多上传API可以上传任意大小的物体。唯一的要求是除了最后的每个“部分”必须至少有5MB,这是这里的问题:fread()返回一个小于5MB大小的字符串。 – Jesse

4

当部分中的一个的尺寸小于5MB并且不是最后部分发生此错误(最后部分可以是任何尺寸)。 fread()可以返回比指定大小更短的字符串,因此在上传该零件之前,您需要始终调用fread(),直到您至少有5MB的数据(或者您已到达文件末尾)。

所以,你的第三步变为:

// 3. Upload the file in parts. 
$file = fopen($filename, 'r'); 
$parts = array(); 
$partNumber = 1; 
while (!feof($file)) { 

    // Get at least 5MB or reach end-of-file 
    $data = ''; 
    $minSize = 5 * 1024 * 1024; 
    while (!feof($file) && strlen($data) < $minSize) { 
     $data .= fread($file, $minSize - strlen($data)); 
    } 

    $result = $client->uploadPart(array(
     'Bucket'  => $bucket, 
     'Key'  => $keyname, 
     'UploadId' => $uploadId, 
     'PartNumber' => $partNumber, 
     'Body'  => $data, // <= send our buffered part 
    )); 
    $parts[] = array(
     'PartNumber' => $partNumber++, 
     'ETag'  => $result['ETag'], 
    ); 
}