Uploading Image to Amazon S3 with HTML, JavaScript & Jquery with Ajax Request (No PHP)

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

Got Amazon S3 & CORS working on js and html5 using XMLHTTPObject based on this article article.

1: CORS only works from a proper URL "http://localhost". (file///xyz will make you go insane)

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!

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

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

 <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!

XUL: Direct upload to S3 but without using a file-input element

From chrome code (aka. privileged code) you can construct DOM File objects simply by just invoking the File constructor with a path:

var file = File("path/to/some/file");
fd.append("file", file);

For more information see: Using the DOM File API in chrome code.

Upload Directly to amazon S3 using AJAX returning error: Bucket POST must contain a field named 'key'

It kind of looks like your file form field is appearing first in the request. I can't tell for sure since you have not included the entire request payload in your answer, but it looks like this is appearing just above the "key" field. AWS ignores all fields in the request after the file field, so all other fields must appear before the file.

Get image data from Html5 canvas and upload it to Amazon S3 server, using Scala

Well i found my answer and much credit goes to this SO post, Get image data in JavaScript?

def foo(source: String) {
//Getting the base64 encoded string, then converting into byte stream
val imgByte = Base64.decodeBase64(source)
val bis = new ByteArrayInputStream(imgByte)

val bucketName = "SOME_BUCKET"
val AWS_ACCESS_KEY = "KEY"
val AWS_SECRET_KEY = "SECRET"

val yourAWSCredentials = new BasicAWSCredentials(AWS_ACCESS_KEY, AWS_SECRET_KEY)
val amazonS3Client = new AmazonS3Client(yourAWSCredentials)
val md = new ObjectMetadata

amazonS3Client.putObject(bucketName, "fireside2.png", bis, md)
}

Asynchronous uploading (HTTP POST) to Amazon S3: why aren't I getting the right callbacks?

After inspecting the XHR object

That error looks like a same-origin-policy violation to me. You can do a form post to another domain, but you can't do an XHR to anything other than the host your JS came from, and I don't see any XHR on the sample you linked.



Related Topics



Leave a reply



Submit