AWS Pre签名的URL

我试图使用PHP / Javascript将图像/视频上传到AWS S3

这是我的PHP代码

<?php
use AwsS3ExceptionS3Exception;


    $filename = isset($_GET['file']) ? $_GET['file'] : '';
    $mime = isset($_GET['mime']) ? $_GET['mime'] : '';

    function getSignedUrl($filename, $mime) {


        require $_SERVER['DOCUMENT_ROOT'].'/ibrainmart/start.php';

        $BUCKET = $config['S3']['bucket'];
        $tmp_name = $filename;



        try {
            $command= $S3->getCommand('PutObject', array(
                    'Bucket'      => $BUCKET,
                    'Key'         => $tmp_name,
                    'ContentType' => $mime,
                    'Body'        => ''

            ));
            $signedUrl = $S3->createPresignedRequest($command, "1 week");
        } catch (S3Exception $e) {
            echo $e->getMessage() . "n";
        }
        echo $signedUrl->getUri();
        return $signedUrl->getUri();
    }


    echo getSignedUrl($filename,$mime);

?>

这是我的Java脚本代码

$(function(){
    // run onLoad

    $("#profilePic").uploadHandler("headerupload.php");
});

// Upload image to S3
$.fn.uploadHandler = function(s3presignedApiUri) 
{
    $(document).ready(function (e) {
        $("#profilePic").on('change',(function(e) {
        e.preventDefault();

        console.log("ajax going to start..!");
        var fileupload = $('input[name=file]');
        var fileToUpload = fileupload[0].files[0];
           if(fileToUpload !="undefined"){
            var formData = new FormData();
            formData.append("file", fileToUpload);
           }
        console.log("fileToUpload.name"+fileToUpload.name);
        $.ajax({
                url: s3presignedApiUri, // Url to which the request is send
                type: "GET",             // Type of request to be send, called as method

                data: 'file='+ fileToUpload.name + '&mime=' + fileToUpload.type , // Data sent to server, a set of key/value pairs (i.e. form fields and values)


                cache: false,             // To unable request pages to be cached
                })       


                .done(function(data)   // A function to be called if request succeeds
                {

                    console.log("data ............"+data);

                    $.ajax({
                        url : data.url,
                        type : "PUT",
                        data : fileToUpload,
                        cache : false,
                        contentType : fileToUpload.type,
                        processData : false
                    })
                    .done(function() {

                        console.info("s3-upload done: "); // REMOVE ME FOR PRODUCTION USE

                    })
                    .fail(function(e) {
                        console.error("s3-upload failed",e); // REMOVE ME FOR PRODUCTION USE
                    });
                })
                .fail(function(e)
                        {
                        console.log("file passing error.!");
                    })

                }));

    });


}

所有这些函数的工作伟大我猜即使执行后,它给了我文件上传成功消息too.but当我检查S3没有什么。

即使在控制台中,它也会生成Presignrd URL,如下图所示。但当我尝试点击它时,它会给我SignatureDoesNotMatch错误(请单击该URL)。什么可能是错误..?

https://ibrainmartstorage.s3.us-east-2.amazonaws.com/DSC_1595.JPG?X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAJZBWQOXKKPC7UXDQ% 2F20170824%2Fus - 东 - 2%2Fs3%2Faws4_request&X-AMZ-日期= 20170824T062933Z&X-AMZ-SignedHeaders =宿主&X-AMZ-过期= 604800&X-AMZ-签名= a4384c737f191c6a516611f67a322ebf98b8e9e0aff65bbcd84e74c87637fb3dhttps://ibrainmartstorage.s3.us-east-2.amazonaws。 COM / DSC_1595.JPG?X-AMZ-内容-SHA256 = UNSIGNED-PAYLOAD&X-AMZ-算法= AWS4-HMAC-SHA256&X-AMZ-凭证= AKIAJZBWQOXKKPC7UXDQ%2F20170824%2Fus - 东 - 2%2Fs3%2Faws4_request&X-AMZ-日期= 20170824T062933Z&X-AMZ-SignedHeaders =宿主&X-AMZ-过期= 604800&X-AMZ-签名= a4384c737f191c6a516611f67a322ebf98b8e9e0aff65bbcd84e74c87637fb3d


尝试几天后发现这个解决方案。

使用AWS Cognito联合池为AWS S3生成会话并使用临时生成的Secret密钥,accessID和Session.Beow上传文件,我列出了代码示例。

getAuthenticateUser().getSession(function(err,session){
     if (err) {
        console.log("Error"+err);
        return;
    }
    if(session.isValid())
    {

        const authenticator = 'cognito-idp.us-east-2.amazonaws.com/us-east-2_cfmOv3jSL';
        AWS.config.region = 'us-east-2'; // Region
        AWS.config.credentials = new AWS.CognitoIdentityCredentials({
        IdentityPoolId: 'us-east-2:XXXXX-d2b7-XXXX-85c7-929aadf450b2',
        Logins: {
            [authenticator]: session.getIdToken().getJwtToken()
          }

    });
     AWS.config.credentials.refresh((error) => {
         if (error) {
             console.error(error);
         } else {
             console.log('Successfully logged!');
         }
    });


    AWS.config.getCredentials(function(err) {
      if (err) console.log(err.stack); // credentials not loaded
      else { 
        console.log("Access Key:", AWS.config.credentials.accessKeyId);
      console.log("Access Key:", AWS.config.credentials.secretAccessKey);
     console.log("Access Key:", AWS.config.credentials);

    AWS.config.update({
        AccessKeyId : AWS.config.credentials.AccessKeyId,
        SecretAccessKey : AWS.config.credentials.SecretAccessKey ,
        SessionToken : AWS.config.credentials.SessionToken

    });
      }

    });
    }

    if(!session.isValid())
    {
        console.log("Session is not valid..!");
         //Please Login to Continue
    }

    });
链接地址: http://www.djcxy.com/p/39047.html

上一篇: AWS Pre signed URL

下一篇: CORS issue with a PreSigned S3 URL for file upload