使用Amazon S3和FineUploader时出错

时间:2013-08-28 06:49:11

标签: php javascript zend-framework amazon-s3 fine-uploader

我正在尝试使用Amazon S3来存储我的文件。另外,我想使用FineUploader将图像上传到亚马逊(我正在使用Zend Framework)。

这是我的观点:

<div id="fineuploader-s3"></div>

这是我的javascript文件:(更改了密钥/存储桶名称)

$(document).ready(function () {
$('#fineuploader-s3').fineUploaderS3({
    request: {
        // REQUIRED: We are using a custom domain
        // for our S3 bucket, in this case.  You can
        // use any valid URL that points to your bucket.
        endpoint: "mybucket.s3.amazonaws.com",

        // REQUIRED: The AWS public key for the client-side user
        // we provisioned.
        accessKey: "mykey"
    },

    // REQUIRED: Path to our local server where requests
    // can be signed.
    signature: {
        endpoint: "/s3/s3demo.php"
    },

    // OPTIONAL: An endopint for Fine Uploader to POST to
    // after the file has been successfully uploaded.
    // Server-side, we can declare this upload a failure
    // if something is wrong with the file.
    uploadSuccess: {
        endpoint: "/s3demo.php?success"
    },

    // USUALLY REQUIRED: Blank file on the same domain
    // as this page, for IE9 and older support.
    iframeSupport: {
        localBlankPagePath: "/server/success.html"
    },

    // optional feature
    retry: {
        showButton: true
    },

    // optional feature
    chunking: {
        enabled: true
    },

    // optional feature
    resume: {
        enabled: true
    },

    // optional feature
    deleteFile: {
        enabled: true,
        method: "POST",
        endpoint: "/s3demo.php"
    },

    // optional feature
    validation: {
        itemLimit: 5,
        sizeLimit: 15000000
    }
});
});

这是文件夹s3中的's3demo.php'文件(在公共文件中,根文件中):(更改了密钥/桶名)

<?php

// You can remove these two lines if you are not using Fine Uploader's
// delete file feature
require 'AWSSDKforPHP/aws.phar';
use Aws\S3\S3Client;

// These assume you have the associated AWS keys stored in
// the associated system environment variables
$clientPrivateKey = $_SERVER['mykey'];
// These two keys are only needed if the delete file feature is enabled
// or if you are, for example, confirming the file size in a successEndpoint
// handler via S3's SDK, as we are doing in this example.
//$serverPublicKey = $_SERVER['PARAM1'];
//$serverPrivateKey = $_SERVER['PARAM2'];

// The following variables are used when validating the policy document
// sent by the uploader. 
$expectedBucketName = "mybucket.s3.amazonaws.com";
// $expectedMaxSize is the value you set the sizeLimit property of the 
// validation option. We assume it is `null` here. If you are performing
// validation, then change this to match the integer value you specified
// otherwise your policy document will be invalid.
// http://docs.fineuploader.com/branch/develop/api/options.html#validation-option
$expectedMaxSize = null;

$method = getRequestMethod();

// This second conditional will only ever evaluate to true if
// the delete file feature is enabled
if ($method == "DELETE") {
    deleteObject();
}
// This is all you really need if not using the delete file feature
// and not working in a CORS environment
else if ($method == 'POST') {

    // Assumes the successEndpoint has a parameter of "success" associated with it,
    // to allow the server to differentiate between a successEndpoint request
    // and other POST requests (all requests are sent to the same endpoint in this example).
    // This condition is not needed if you don't require a callback on upload success.
    if (isset($_REQUEST["success"])) {
        verifyFileInS3();
    }
    else {
        signRequest();
    }
}

// This will retrieve the "intended" request method.  Normally, this is the
// actual method of the request.  Sometimes, though, the intended request method
// must be hidden in the parameters of the request.  For example, when attempting to
// send a DELETE request in a cross-origin environment in IE9 or older, it is not
// possible to send a DELETE request.  So, we send a POST with the intended method,
// DELETE, in a "_method" parameter.
function getRequestMethod() {

    if ($_POST['_method'] != null) {
        return $_POST['_method'];
    }

    return $_SERVER['REQUEST_METHOD'];
}

function getS3Client() {
    global $serverPublicKey, $serverPrivateKey;

    return S3Client::factory(array(
        'key' => $serverPublicKey,
        'secret' => $serverPrivateKey
    ));
}

// Only needed if the delete file feature is enabled
function deleteObject() {
    getS3Client()->deleteObject(array(
        'Bucket' => $_POST['bucket'],
        'Key' => $_POST['key']
    ));
}

function signRequest() {
    header('Content-Type: application/json');

    $responseBody = file_get_contents('php://input');
    $contentAsObject = json_decode($responseBody, true);
    $jsonContent = json_encode($contentAsObject);

    $headersStr = $contentAsObject["headers"];
    if ($headersStr) {
        signRestRequest($headersStr);
    }
    else {
        signPolicy($jsonContent);
    }
}

function signRestRequest($headersStr) {
    if (isValidRestRequest($headersStr)) {
        $response = array('signature' => sign($headersStr));
        echo json_encode($response);
    }
    else {
        echo json_encode(array("invalid" => true));
    }
}

function isValidRestRequest($headersStr) {
    global $expectedBucketName;

    $pattern = "/\/$expectedBucketName\/.+$/";
    preg_match($pattern, $headersStr, $matches);

    return count($matches) > 0;
}

function signPolicy($policyStr) {
    $policyObj = json_decode($policyStr, true);

    if (isPolicyValid($policyObj)) {
        $encodedPolicy = base64_encode($policyStr);
        $response = array('policy' => $encodedPolicy, 'signature' => sign($encodedPolicy));
        echo json_encode($response);
    }
    else {
        echo json_encode(array("invalid" => true));
    }
}

function isPolicyValid($policy) {
    global $expectedMaxSize, $expectedBucketName;

    $conditions = $policy["conditions"];
    $bucket = null;
    $parsedMaxSize = null;

    for ($i = 0; $i < count($conditions); ++$i) {
        $condition = $conditions[$i];

        if (isset($condition["bucket"])) {
            $bucket = $condition["bucket"];
        }
        else if (isset($condition[0]) && $condition[0] == "content-length-range") {
            $parsedMaxSize = $condition[2];
        }
    }

    return $bucket == $expectedBucketName && $parsedMaxSize == (string)$expectedMaxSize;
}

function sign($stringToSign) {
    global $clientPrivateKey;

    return base64_encode(hash_hmac(
            'sha1',
            $stringToSign,
            $clientPrivateKey,
            true
        ));
}

// This is not needed if you don't require a callback on upload success.
function verifyFileInS3() {
    global $expectedMaxSize;

    $bucket = $_POST["bucket"];
    $key = $_POST["key"];

    // If utilizing CORS, we return a 200 response with the error message in the body
    // to ensure Fine Uploader can parse the error message in IE9 and IE8,
    // since XDomainRequest is used on those browsers for CORS requests.  XDomainRequest
    // does not allow access to the response body for non-success responses.
    if (getObjectSize($bucket, $key) > $expectedMaxSize) {
        // You can safely uncomment this next line if you are not depending on CORS
        header("HTTP/1.0 500 Internal Server Error");
        deleteObject();
        echo json_encode(array("error" => "File is too big!"));
    }
    else {
        echo json_encode(array("tempLink" => getTempLink($bucket, $key)));
    }
}

// Provide a time-bombed public link to the file.
function getTempLink($bucket, $key) {
    $client = getS3Client();
    $url = "{$bucket}/{$key}";
    $request = $client->get($url);

    return $client->createPresignedUrl($request, '+15 minutes');
}

function getObjectSize($bucket, $key) {
    $objInfo = getS3Client()->headObject(array(
            'Bucket' => $bucket,
            'Key' => $key
        ));
    return $objInfo['ContentLength'];
}
?>

我收到了这个错误:

  

[FineUploader 3.8.0]尝试解析签名响应时出错:SyntaxError:意外的令牌&lt; s3.jquery.fineuploader-3.8.0.min.js:16
  [FineUploader 3.8.0]从服务器收到空的或无效的响应! s3.jquery.fineuploader-3.8.0.min.js:16
  [FineUploader 3.8.0]策略签名失败。从服务器收到空的或无效的响应! s3.jquery.fineuploader-3.8.0.min.js:16

第一个错误显示我的s3demo.php文件有问题...(令牌&lt; - &gt;我的第一个php文件)

回应 - 标题:

  

请求网址:http://www.link.com/s3/s3demo.php
  请求方法:POST
  状态代码:200 OK
  请求Headersview来源
  接受: /
  接受编码:gzip,紧缩,SDCH
  接受语言:NL-NL,NL; Q = 0.8,EN-US; Q = 0.6,连接; Q = 0.4
  缓存控制:无缓存
  连接:保持活跃
  内容长度:292
  内容类型:应用/ JSON;字符集= UTF-8
  饼干:PHPSESSID =
  主持人:www.link.com
  起源:http://www.link.com
  附注:无缓存
  引用者:http://www.link.com/quiz/design
  用户代理:Mozilla / 5.0(Macintosh; Intel Mac OS X 10_6_8)AppleWebKit / 537.36(KHTML,与Gecko一样)Chrome / 29.0.1547.57 Safari / 537.36
  请求Payloadview来源
  {失效:2013-08-28T15:35:56.160Z,...}
  条件:[{acl:private},{bucket:mybucket},{Content-Type:image / png},{success_action_status:200},...]   到期日:“2013-08-28T15:35:56.160Z”
  响应标题查看源
  连接:保持活动
  内容长度:2504
  内容类型:应用程序/ JSON
  日期:2013年8月28日星期三格林威治标准时间15:30:55   保持活跃:超时= 5,最大= 90
  服务器:Apache / 2.2.22(Debian)
  X-已启动通过:PHP / 5.5.1-1〜dotdeb.1

实际回应:

  


     (!)注意:未定义的索引:_var/www/site/public/s3/s3demo.php中的_method 79   调用堆栈   #TimeMemoryFunctionLocation   10.0047235456 {main}()../ s3demo.php 0   20.0323825744getRequestMethod()../ s3demo.php 48      
     (!)注意:未定义索引:第 110 行中s3 / s3demo.php中的标题   调用堆栈   #TimeMemoryFunctionLocation   10.0047235456 {main}()../ s3demo.php 0   20.0325825896signRequest()../ s3demo.php 67      { “无效”:真}

1 个答案:

答案 0 :(得分:1)

我认为您不太了解文档或示例。您需要一个服务器端组件来签署Fine Uploader发送的请求。由于某种原因,您似乎将Fine Uploader指向JSON文件。我猜你是从博客文章复制了示例签名文件,并指向Fine Uploader?博客文章中详细介绍了示例签名文件,以便您了解Fine Uploader S3如何为您的简单上传生成策略文档。您无需在任何地方存储此副本。

您需要一个合适的服务器端组件来签署Fine Uploader至少发送给S3的请求。在https://github.com/Widen/fine-uploader-server中,Fine Uploader S3已经有5个功能齐全的服务器端示例。实际上,博客文章链接到用node,python,php和java编写的示例。您还应该仔细查看博客文章或文档。