You can connect to and manage S3 Storage using the AWS JavaScript SDK.
The methods described below are relevant for AWS SDK version 2.742.0
Include aws sdk in your HTML page
The example shows how to include AWS JavaScript SDK 2.742.0 https://sdk.amazonaws.com/js/aws-sdk-2.742.0.min.js in your HTML page.
The AWS JavaScript SDK 2.742.0 version can be found here.
<html>
<head>
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.742.0.min.js"></script>
<script src="./js/index2.js"></script>
</head>
<body>
<h1>List of files</h1>
<ul id="list">
</ul>
</body>
</html>
Configure storage and create s3 bucket
Open the configuration file ./js/index2.js and specify the data of your storage and future bucket:
var s3BucketName = "test_2";
var host = "https://s-ed1.cloud.gcore.lu";
var access_key = "1234";
var secret_key = "5678";
AWS.config.accessKeyId = access_key;
AWS.config.secretAccessKey = secret_key;
AWS.config.endpoint = host;
var s3 = new AWS.S3({
sslEnabled: true
});
Where:
test_2 is the name of the future bucket
https://s-ed1.cloud.gcore.lu is the storage URL
1234 is the access key, you received when creating the storage in the personal account.
5678 is the secret key, you received when creating the storage in the personal account.
Set CORS policy on a bucket via s3cmd:
Wildcard policy example
The example describes a configuration that allows cross-origin GET HEAD PUT, POST and DELETE requests from all sources.
Attention! This configuration can be insecure.
<CORSConfiguration>
<CORSRule>
<ID>Allow
everything</ID>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>HEAD</AllowedMethod>
<AllowedMethod>PUT</AllowedMethod>
<AllowedMethod>POST</AllowedMethod>
<AllowedMethod>DELETE</AllowedMethod>
<AllowedHeader>*</AllowedHeader>
<MaxAgeSeconds>30</MaxAgeSeconds>
</CORSRule>
</CORSConfiguration>
After the configuration is created, apply it to the bucket.
s3cmd setcors cors.xml s3://<bucket_name>
Add files to bucket
The example shows how to add two files (test_file1 and test_file2) to the s3BucketName bucket.
var params1 = {
Bucket: s3BucketName, Key: 'test_file1',
Body: "test"
};
var params2 = {
Bucket: s3BucketName, Key: 'test_file2',
Body: "test"
};
var request = s3.putObject(params1);
request.send(function (err, data) {
if (err) console.log("Error:", err.code, err.message);
else console.log(data);
});
var request = s3.putObject(params2);
request.send(function (err, data) {
if (err) console.log("Error:", err.code, err.message);
else console.log(data);
});
Get a list of files
The example shows how to get a list of files located in the test_2 bucket.
params = {
Bucket: "test_2"
};
s3.listObjects(params, function(err, data) {
if (err) return;
data.Contents.map(function(info){
var ul = document.getElementById("list");
var li = document.createElement("li");
li.innerText = info.Key + " " + info.LastModified;
ul.append(li);
});
});
An example of the result: