簡體   English   中英

使用 Ajax 請求(無 PHP)使用 HTML、javascript 和 jQuery 將圖像上傳到 Amazon s3

[英]Uploading Image to Amazon s3 with HTML, javascript & jQuery with Ajax Request (No PHP)

我正在用 HTML、javascript 和 jQuery 開發一個網站。 我想在 ajax 請求中將圖像上傳到 amazon s3 服務器。 沒有這樣的 SDK 可以在 Javascript 中集成 s3。 PHP SDK 可用,但對我沒有用。 任何人都可以在 javascript 中提供解決方案嗎?

根據這篇文章,使用 XMLHTTPObject 使 Amazon S3 和 CORS 在 js 和 html5 上工作。

1:CORS 僅適用於正確的 URL“ http://localhost ”。 (文件///xyz 會讓你發瘋)

2:確保您正確編譯了 POLICY 和 Secret - 這是我的政策,這是您可以獲得項目的鏈接,可以讓您開始使用Signature 和 Policy - 永遠不要用您的 Secret 發布這個 JS!

POLICY_JSON = { "expiration": "2020-12-01T12:00:00.000Z",
            "conditions": [
            {"bucket": this.get('bucket')},
            ["starts-with", "$key", ""],
            {"acl": this.get('acl')},                           
            ["starts-with", "$Content-Type", ""],
            ["content-length-range", 0, 524288000]
            ]
          };


    var secret = this.get('AWSSecretKeyId');
    var policyBase64 = Base64.encode(JSON.stringify(POLICY_JSON));
    console.log ( policyBase64 )

    var signature = b64_hmac_sha1(secret, policyBase64);
    b64_hmac_sha1(secret, policyBase64);
    console.log( signature);

這是JS代碼

function uploadFile() {

    var file = document.getElementById('file').files[0];
    var fd = new FormData();

    var key = "events/" + (new Date).getTime() + '-' + file.name;

    fd.append('key', key);
    fd.append('acl', 'public-read'); 
    fd.append('Content-Type', file.type);      
    fd.append('AWSAccessKeyId', 'YOUR ACCESS KEY');
    fd.append('policy', 'YOUR POLICY')
    fd.append('signature','YOUR SIGNATURE');

    fd.append("file",file);

    var xhr = new XMLHttpRequest();

    xhr.upload.addEventListener("progress", uploadProgress, false);
    xhr.addEventListener("load", uploadComplete, false);
    xhr.addEventListener("error", uploadFailed, false);
    xhr.addEventListener("abort", uploadCanceled, false);

    xhr.open('POST', 'https://<yourbucket>.s3.amazonaws.com/', true); //MUST BE LAST LINE BEFORE YOU SEND 

    xhr.send(fd);
  }

輔助功能

function uploadProgress(evt) {
    if (evt.lengthComputable) {
      var percentComplete = Math.round(evt.loaded * 100 / evt.total);
      document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';
    }
    else {
      document.getElementById('progressNumber').innerHTML = 'unable to compute';
    }
  }

  function uploadComplete(evt) {
    /* This event is raised when the server send back a response */
    alert("Done - " + evt.target.responseText );
  }

  function uploadFailed(evt) {
    alert("There was an error attempting to upload the file." + evt);
  }

  function uploadCanceled(evt) {
    alert("The upload has been canceled by the user or the browser dropped the connection.");
  }

然后是 HTML 表單

 <form id="form1" enctype="multipart/form-data" method="post">
<div class="row">
  <label for="file">Select a File to Upload</label><br />
  <input type="file" name="file" id="file" onchange="fileSelected()"/>
</div>
<div id="fileName"></div>
<div id="fileSize"></div>
<div id="fileType"></div>
<div class="row">
  <input type="button" onclick="uploadFile()" value="Upload" />
</div>
<div id="progressNumber"></div>

CORS-ing 快樂!

亞馬遜剛剛允許跨源資源共享,理論上它允許您的用戶直接上傳到 S3,而無需使用您的服務器(和 PHP)作為代理。

這是文檔 ->http://docs.amazonwebservices.com/AmazonS3/latest/dev/cors.html

他們很好地告訴您如何在 S3 存儲桶上啟用它,但 iv 沒有找到有關如何從客戶端獲取數據到存儲桶的實際 javascript 示例。

第一個發布 CORS.js 的人是一個傳奇 xD

我正在用 HTML、javascript 和 jQuery 開發一個網站。 我想在 ajax 請求中將圖像上傳到亞馬遜 s3 服務器。 沒有這樣的 SDK 可以將 s3 集成到 Javascript 中。 PHP SDK 可用,但對我沒有用。 有人可以在javascript中為此提供解決方案嗎?

您可以通過 AWS S3 Cognito 執行此操作,請在此處嘗試此鏈接:

http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/browser-examples.html#Amazon_S3

也試試這個代碼

只需更改區域、IdentityPoolId 和您的存儲桶名稱

<!DOCTYPE html>
<html>

<head>
    <title>AWS S3 File Upload</title>
    <script src="https://sdk.amazonaws.com/js/aws-sdk-2.1.12.min.js"></script>
</head>

<body>
    <input type="file" id="file-chooser" />
    <button id="upload-button">Upload to S3</button>
    <div id="results"></div>
    <script type="text/javascript">
    AWS.config.region = 'your-region'; // 1. Enter your region
    AWS.config.credentials = new AWS.CognitoIdentityCredentials({
        IdentityPoolId: 'your-IdentityPoolId' // 2. Enter your identity pool
    });
    AWS.config.credentials.get(function(err) {
        if (err) alert(err);
        console.log(AWS.config.credentials);
    });
    var bucketName = 'your-bucket'; // Enter your bucket name
    var bucket = new AWS.S3({
        params: {
            Bucket: bucketName
        }
    });
    var fileChooser = document.getElementById('file-chooser');
    var button = document.getElementById('upload-button');
    var results = document.getElementById('results');
    button.addEventListener('click', function() {
        var file = fileChooser.files[0];
        if (file) {
            results.innerHTML = '';
            var objKey = 'testing/' + file.name;
            var params = {
                Key: objKey,
                ContentType: file.type,
                Body: file,
                ACL: 'public-read'
            };
            bucket.putObject(params, function(err, data) {
                if (err) {
                    results.innerHTML = 'ERROR: ' + err;
                } else {
                    listObjs(); // this function will list all the files which has been uploaded
                    //here you can also add your code to update your database(MySQL, firebase whatever you are using)
                }
            });
        } else {
            results.innerHTML = 'Nothing to upload.';
        }
    }, false);
    function listObjs() {
        var prefix = 'testing';
        bucket.listObjects({
            Prefix: prefix
        }, function(err, data) {
            if (err) {
                results.innerHTML = 'ERROR: ' + err;
            } else {
                var objKeys = "";
                data.Contents.forEach(function(obj) {
                    objKeys += obj.Key + "<br>";
                });
                results.innerHTML = objKeys;
            }
        });
    }
    </script>
</body>

</html>

如果需要,您可以使用github 鏈接

我希望它能幫助別人:)

對於身份驗證部分,

沒有 php 代碼,沒有服務器,除了下面沒有大的 JS 代碼;

您可以使用 AWS Cognito IdentityPoolId 作為憑據,代碼更少,但您需要創建 AWS Cognito IdetityPool 並附加策略,只需 s3 寫入訪問權限。

     var IdentityPoolId = 'us-east-1:1...........';


     AWS.config.update({
        credentials: new AWS.CognitoIdentityCredentials({
            IdentityPoolId: IdentityPoolId
        })
     });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM