Uploading files from HTML page to an StorageVault S3 bucket

Table of contents

  1. Introduction
    1. Source code
    2. Insert correct access data to the bucket.
    3. Let’s test it in the browser
    4. Let’s install a CORS policy for our bucket
    5. Final testing
  2. Conclusion
  3. Useful links

 

Introduction

In this article, we will learn how to create a simple HTML page with a form for uploading files into the object storage s3.

For the solution of this particular task will be used javascript aws-sdk library and s3cmd tool.

Source code

Let’s create index.html with the following content:

<!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">
const ENDPOINT_URL = "https://s3.pilw.io"
const ACCESS_KEY_ID = "ENTER ACCESS KEY ID HERE"
const ACCESS_KEY_SECRET = "ENTER ACCESS KEY SECRET"
const BUCKET_NAME = "ENTER BUCKET NAME HERE"
 
var bucket = new AWS.S3({
    accessKeyId: ACCESS_KEY_ID,
    secretAccessKey: ACCESS_KEY_SECRET,
    endpoint: new AWS.Endpoint(ENDPOINT_URL),
    params: {
        Bucket: BUCKET_NAME
    }
})
 
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]
    results.innerHTML = ''
    if (!file) {
        results.innerHTML = 'Nothing to upload.'
        return
    }
    var params = {
        Key: 'demo/' + file.name,
        ContentType: file.type,
        Body: file,
        ACL: 'public-read'
    }
    bucket.putObject(params, function(err, data) {
        if (err) {
            results.innerHTML = 'ERROR: ' + err;
            return
         }
         listObjs()
    })
}, false)
 
function listObjs() {
    bucket.listObjects({Prefix: 'demo'}, function(err, data) {
        if (err) {
            results.innerHTML = 'ERROR: ' + err;
            return
        }
        var objKeys = "";
        data.Contents.forEach(function(obj) {
            objKeys += obj.Key + "<br>"
        });
        results.innerHTML = objKeys
    })
}
</script>
</body>
</html>

Insert correct access data to the bucket.

In this step we need to set correct values for the following constants:

    • ACCESS_KEY_ID (14. line of the source code)
    • ACCESS_KEY_SECRET (15. line of the source code)
    • BUCKET_NAME (16. Line of the source code)

 

You can also find values of ACCESS_KEY_ID and ACCESS_KEY_SECRET in the information about the bucket in the storage control panel. If you don’t have a bucket, we suggest you familiarize yourself with this manual: how to create a bucket.

Let’s test it in the browser

Open index.html in a browser. In the process of testing turns out that file uploading is not working: error Cross-origin request blocked. In the process of testing turns out that file uploading is not working: error Cross-origin request blocked.

 

Let’s install a CORS policy for our bucket

To fix the Cross-Origin Request Blocked error we need to prepare special XML file rules.xml, where we are going to describe such parameters as AllowedOrigin, AllowedMethod, AllowedHeader. In the rules.xml file will be described CORS policy for our bucket. This particular policy is setting up for each bucket individually. To apply a set of rules for the bucket, we should use the s3cmd command line or the analog. Let’s create a file rules.xml with the following content:

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<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>

IMPORTANT! This configuration cannot be considered safe. It is not recommended to use this configuration in production. It is possible to use it only as a demonstration.

Let’s apply this policy to our bucket using the s3cmd tool.
$ s3cmd -c s3test.cfg setcors rules.xml s3://corsexample

In this case, “corsexample” is the name of our bucket, rules.xml is the file with cors policies, and s3test.cfg is the file of the configuration of s3cmd tool.

Final testing

After applying CORS parameters, files uploaded successfully.

If there are any reasons to delete the CORS configuration for the bucket, you can run the command:

$ s3cmd -c s3test.cfg delcors s3://corsexample

Conclusion

As the example of this article, we can relate to the interaction of the frontend with s3 storage.

As we remember from the previous article, s3 allows us to keep and serve statics. It also can be hosting for our website.

We can also adapt this particular code for working with a backend. We will talk about it in our next article.

As a result, web app integration with s3 storage is not a big deal.

 

Share on facebook
Share on linkedin
Share on twitter
Share on pinterest
Share on email

Seotud uudised