使用Ajax请求将图像上载到Amazon S3,使用JavaScript和jQuery(不使用PHP)
我正在开发一个HTML,JavaScript和jQuery的网站。 我想在ajax请求上传图片到amazon s3服务器。 没有这样的SDK来整合s3在Javascript中。 一个PHP SDK是可用的,但它对我没有用处。 任何人都可以提供解决这个在JavaScript?
根据这篇文章文章,使用XMLHTTPObject获得Amazon S3和CORS在js和html5上的工作。
1:CORS只能从一个合适的URL“ http:// localhost ”工作。 (文件/// xyz会让你疯了)
2:确保你的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 = getXMLHTTPObject(); 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
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存储桶上启用它,但是没有find如何从客户端获取数据的实际javascript示例。
第一个发布CORS.js的人是一个传奇xD
以下是使用CORS和JavaScript在Amazon S3上可恢复file upload的示例http://cotag.github.com/Condominios/
您可以通过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="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链接
我希望它会帮助别人:)
对于authentication部分,
没有php代码,没有服务器,除了下面没有大的JS代码;
您可以使用AWS Cognito IdentityPoolId作为凭据,代码less,但您需要创buildAWS Cognito IdetityPool和附加策略,只需s3写入权限即可。
var IdentityPoolId ='us-east-1:1 ...........'; AWS.config.update({ 凭证:新AWS.CognitoIdentityCredentials({ IdentityPoolId:IdentityPoolId }) });