简体   繁体   English

使用 Ajax 请求(无 PHP)使用 HTML、javascript 和 jQuery 将图像上传到 Amazon s3

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

I am developing a website in HTML, javascript & jQuery.我正在用 HTML、javascript 和 jQuery 开发一个网站。 I want to upload images to amazon s3 server in an ajax request.我想在 ajax 请求中将图像上传到 amazon s3 服务器。 There is no such SDK to integrate s3 in Javascript.没有这样的 SDK 可以在 Javascript 中集成 s3。 A PHP SDK is available, but it is not useful to me. PHP SDK 可用,但对我没有用。 Can anybody provide solution to this in javascript?任何人都可以在 javascript 中提供解决方案吗?

Got Amazon S3 & CORS working on js and html5 using XMLHTTPObject based on this article article .根据这篇文章,使用 XMLHTTPObject 使 Amazon S3 和 CORS 在 js 和 html5 上工作。

1: CORS only works from a proper URL " http://localhost ". 1:CORS 仅适用于正确的 URL“ http://localhost ”。 (file///xyz will make you go insane) (文件///xyz 会让你发疯)

2: Make sure you got the POLICY and Secret compiled correctly - here is my policy and this is the link you can get the project to get you started with Signature and Policy -- do not publish this JS with your Secret EVER! 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);

Here is the JS code这是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);
  }

Helper functions辅助功能

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.");
  }

Then the HTML Form然后是 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>

Happy CORS-ing! CORS-ing 快乐!

Amazon just allowed Cross-Origin Resource Sharing, in theory it allows your users to upload to S3 directly, without using your server (and PHP) as a proxy.亚马逊刚刚允许跨源资源共享,理论上它允许您的用户直接上传到 S3,而无需使用您的服务器(和 PHP)作为代理。

Heres the docs ->http://docs.amazonwebservices.com/AmazonS3/latest/dev/cors.html这是文档 ->http://docs.amazonwebservices.com/AmazonS3/latest/dev/cors.html

They do a great job of telling you how to enable it on an S3 bucket, but iv found no actual javascript examples of how to get data from client to bucket.他们很好地告诉您如何在 S3 存储桶上启用它,但 iv 没有找到有关如何从客户端获取数据到存储桶的实际 javascript 示例。

First person to post CORS.js is a legend xD第一个发布 CORS.js 的人是一个传奇 xD

I am developing a website in HTML, javascript & jQuery.我正在用 HTML、javascript 和 jQuery 开发一个网站。 I want to upload images to amazon s3 server in an ajax request.我想在 ajax 请求中将图像上传到亚马逊 s3 服务器。 There is no such SDK to integrate s3 in Javascript.没有这样的 SDK 可以将 s3 集成到 Javascript 中。 A PHP SDK is available, but it is not useful to me. PHP SDK 可用,但对我没有用。 Can anybody provide solution to this in javascript?有人可以在javascript中为此提供解决方案吗?

You can do this by AWS S3 Cognito try this link here:您可以通过 AWS S3 Cognito 执行此操作,请在此处尝试此链接:

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

Also try this code也试试这个代码

Just change Region, IdentityPoolId and Your bucket name只需更改区域、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>

If needed you can use github Link如果需要,您可以使用github 链接

I hope it will help others:)我希望它能帮助别人:)

For the authentication part,对于身份验证部分,

No php code, no server, no large JS code except below;没有 php 代码,没有服务器,除了下面没有大的 JS 代码;

you might use AWS Cognito IdentityPoolId as credential, less code but you are required to create AWS Cognito IdetityPool and attach policy, simply s3 write access.您可以使用 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