Reputation: 5689
I'm working on uploading files to an S3 bucket using temporary credentials received from AWS Cognito and I'm getting really rather frustrated. I have access to the access-token
but I'm getting lost trying to initialise the AWS S3 client. Presently I'm storing the access-token
and idToken
in a cookie (though that will change).
When I get to my upload page I have a file input and file upload button and want to upload the file on the button being pressed... but I can't figure out how to do it and I'm feeling really, really, stupid wading through the documentation to no avail.
This is my code so far:
(function(){
var fileSource = $("#fileSource");
fileSource.on("change", function(){
var filePath = $(this).val().split("\\");
$("#upload-file-info").html(filePath[filePath.length - 1]);
});
console.log("accessToken", accessToken);
console.log("idToken", idToken);
AWS.config.region = Region;
var bucket = new AWS.S3({
params: {
Bucket: bucketName + "/" + idToken["cognito:username"]
}
});
console.log(bucket);
$("#uploadButton").on("click", function(){
if(!window.FileReader){
return alert("FileReader API is not supported by your browser.");
}
var input = fileSource[0];
if(input.files && input.files[0]){
file = input.files[0];
fr = new FileReader();
fr.onload = function () {
var objKey = bucketName + "/" + idToken["cognito:username"] + '/' + file.name;
var params = {
Key: objKey,
ContentType: file.type,
Body: file
};
console.log(params);
bucket.putObject(params, function (err, data) {
if (err) {
console.log("arguments", arguments)
} else {
console.log("arguments", arguments)
}
});
};
fr.readAsDataURL( file );
} else {
alert("File not selected or browser incompatible.")
}
});
})();
bucketName
is defined in another file as is the method for retrieving and decoding the cookies.
If someone could point me in the right direction I'd be grateful as I know I'm missing something! Even a pointer to a repo where someone has got this working would be helpful.
(I like the idea of this serverless stuff, but it's a head-scratcher me changing paradigms like this)
Upvotes: 2
Views: 929
Reputation: 5689
Found much of my own answer to this while still knuckle dragging through the documentation. Basically, the Javascript SDK puts most of what I needed into local storage for me, so no messing around with cookies required (I only clocked this after moving away from cookies and using local storage for myself though, that and inspecting local storage ;-) ). I'm still not there yet though but I'm making some progress and I might have to ask a further question later.
Upvotes: 2