Days
Hours
Minutes
Seconds
x
Skip to content

Python Image S3 Upload

How it works

  1. Create a bucket on Amazon S3 and set the CORS for it.
  2. Code computes the Amazon S3 signature on the server side.
  3. The editor initializes with the imageUploadToS3 option.
  4. Uploaded images go directly to the S3 bucket without passing through the server.

Jump to Complete Example

Create a S3 Bucket

For information on creating a bucket and setting a region, refer to the Amazon documentation. If you have any issues creating it, please contact Amazon for getting it set up.

Set CORS on the S3 Bucket

Cross-origin resource sharing (CORS) tells Amazon from which domains to accept requests and what kind of requests. For a detailed explanation of how that works, refer to the Amazon CORS Documentation.

The following example shows the recomended configuration, remember to replace ALLOWED_URL with the URL of the page where you are using editor:

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <CORSRule>
        <AllowedOrigin>ALLOWED_URL</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <AllowedMethod>POST</AllowedMethod>
        <AllowedMethod>PUT</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
</CORSConfiguration>

Compute Signature

To send uploaded images to S3, it is necessary to compute a signature using the AWS access key ID and AWS secret access key and provide it together with the upload request. The editor Python SDK comes with methods to compute the S3 signature using the V4 signing algorithm that works with buckets created on any of the S3 regions.

config = {
  # The name of your bucket.
  'bucket': 'bucket-name',

  # S3 region. If you are using the default us-east-1, it this can be ignored.
  'region': 'eu-west-1',

  # The folder where to upload the images.
  'keyStart': 'uploads',

  # File access.
  'acl': 'public-read',

  # AWS keys.
  'accessKey': YOUR_AWS_ACCESS_KEY,
  'secretKey': YOUR_AWS_SECRET_KEY
}

s3Hash = S3.getHash(config)

Initialize the Javascript editor

To upload images to Amazon S3, set the imageUploadToS3 option on initialization. The editor Python SDK computes the hash required for this as the response of the S3.getHash method.

<script>
$.get( '/get_signature', {})
.done(function( s3Hash ) {
  $('#edit-amazon').froalaEditor({
    imageUploadToS3: s3Hash
  })
});
</script>

Complete Example

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <CORSRule>
        <AllowedOrigin>ALLOWED_URL</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <AllowedMethod>POST</AllowedMethod>
        <AllowedMethod>PUT</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
</CORSConfiguration>
# Django
from django.http import HttpResponse
import json
from froala_editor import S3

def get_signature(request):
  config = {
    # The name of your bucket.
    'bucket': 'bucket-name',

    # S3 region. If you are using the default us-east-1, it this can be ignored.
    'region': 'eu-west-1',

    # The folder where to upload the images.
    'keyStart': 'uploads',

    # File access.
    'acl': 'public-read',

    # AWS keys.
    'accessKey': YOUR_AWS_ACCESS_KEY,
    'secretKey': YOUR_AWS_SECRET_KEY
  }
  try:
    response = S3.getHash(config)
  except Exception:
    response = {'error': str(sys.exc_info()[1])}
  return HttpResponse(json.dumps(response), content_type="application/json")
# Flask
from flask import jsonify
from froala_editor import S3

@app.route('/get_signature')
def get_signature():
  config = {
    # The name of your bucket.
    'bucket': 'bucket-name',

    # S3 region. If you are using the default us-east-1, it this can be ignored.
    'region': 'eu-west-1',

    # The folder where to upload the images.
    'keyStart': 'uploads',

    # File access.
    'acl': 'public-read',

    # AWS keys.
    'accessKey': YOUR_AWS_ACCESS_KEY,
    'secretKey': YOUR_AWS_SECRET_KEY
  }
  try:
    response = S3.getHash(config)
  except Exception:
    response = {'error': str(sys.exc_info()[1])}
  return jsonify(**response)
# Pyramid
from froala_editor import S3

def get_signature(request):
  config = {
    # The name of your bucket.
    'bucket': 'bucket-name',

    # S3 region. If you are using the default us-east-1, it this can be ignored.
    'region': 'eu-west-1',

    # The folder where to upload the images.
    'keyStart': 'uploads',

    # File access.
    'acl': 'public-read',

    # AWS keys.
    'accessKey': YOUR_AWS_ACCESS_KEY,
    'secretKey': YOUR_AWS_SECRET_KEY
  }
  try:
    response = S3.getHash(config)
  except Exception:
    response = {'error': str(sys.exc_info()[1])}
  return response
<script>
  $.get( '/get_signature', {})
  .done(function( s3Hash ) {
    $('.selector').froalaEditor({
      fileUploadToS3: s3Hash
    })
  });
</script>

How it works

  1. You create a bucket on Amazon S3 and set the CORS for it.
  2. Your code computes the Amazon S3 signature on server side.
  3. The javascript editor is initialized with the imageUploadToS3 option.
  4. When an image is uploaded, it is being sent directly to the S3 bucket without touching your server.

Jump to Complete Example

Create a S3 Bucket

Amazon explains in detail on the URL below how to create a bucket and set a region for it. If you have any troubles with creating it, please contact Amazon for getting it set up.

http://docs.aws.amazon.com/AmazonS3/latest/gsg/CreatingABucket.html

Set CORS on the S3 Bucket

Cross-origin resource sharing (CORS) mainly tells Amazon from which domains to accept requests and what kind of requests. A detailed explanation of how that works can be find in Amazon Documentation.

We recommend to add a configuration like the one below where you would replace the ALLOWED_URL with the URL of the page where you're using the javascript editor.

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <CORSRule>
        <AllowedOrigin>ALLOWED_URL</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <AllowedMethod>POST</AllowedMethod>
        <AllowedMethod>PUT</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
</CORSConfiguration>

Compute Signature

In order to get the image uploaded to S3, it is necessary to compute a signature using the AWS access key ID and AWS secret access key and provide it together with the upload request. The rich text editor Python SDK comes with methods to compute the S3 signature using the V4 signing algorithm that works with buckets created on any of the S3 regions.

config = {
  # The name of your bucket.
  'bucket': 'bucket-name',

  # S3 region. If you are using the default us-east-1, it this can be ignored.
  'region': 'eu-west-1',

  # The folder where to upload the images.
  'keyStart': 'uploads',

  # File access.
  'acl': 'public-read',

  # AWS keys.
  'accessKey': YOUR_AWS_ACCESS_KEY,
  'secretKey': YOUR_AWS_SECRET_KEY
}

s3Hash = S3.getHash(config)

Initialize the Javascript editor

To get images uploaded to Amazon S3, the imageUploadToS3 option should be set on initialization. The editor Python SDK computes the hash required for this as the response of the S3.getHash method.

<script>
$.get( '/get_signature', {})
.done(function( s3Hash ) {
  $('#edit-amazon').froalaEditor({
    imageUploadToS3: s3Hash
  })
});
</script>

Complete Example

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <CORSRule>
        <AllowedOrigin>ALLOWED_URL</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <AllowedMethod>POST</AllowedMethod>
        <AllowedMethod>PUT</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
</CORSConfiguration>
# Django
from django.http import HttpResponse
import json
from froala_editor import S3

def get_signature(request):
  config = {
    # The name of your bucket.
    'bucket': 'bucket-name',

    # S3 region. If you are using the default us-east-1, it this can be ignored.
    'region': 'eu-west-1',

    # The folder where to upload the images.
    'keyStart': 'uploads',

    # File access.
    'acl': 'public-read',

    # AWS keys.
    'accessKey': YOUR_AWS_ACCESS_KEY,
    'secretKey': YOUR_AWS_SECRET_KEY
  }
  try:
    response = S3.getHash(config)
  except Exception:
    response = {'error': str(sys.exc_info()[1])}
  return HttpResponse(json.dumps(response), content_type="application/json")
# Flask
from flask import jsonify
from froala_editor import S3

@app.route('/get_signature')
def get_signature():
  config = {
    # The name of your bucket.
    'bucket': 'bucket-name',

    # S3 region. If you are using the default us-east-1, it this can be ignored.
    'region': 'eu-west-1',

    # The folder where to upload the images.
    'keyStart': 'uploads',

    # File access.
    'acl': 'public-read',

    # AWS keys.
    'accessKey': YOUR_AWS_ACCESS_KEY,
    'secretKey': YOUR_AWS_SECRET_KEY
  }
  try:
    response = S3.getHash(config)
  except Exception:
    response = {'error': str(sys.exc_info()[1])}
  return jsonify(**response)
# Pyramid
from froala_editor import S3

def get_signature(request):
  config = {
    # The name of your bucket.
    'bucket': 'bucket-name',

    # S3 region. If you are using the default us-east-1, it this can be ignored.
    'region': 'eu-west-1',

    # The folder where to upload the images.
    'keyStart': 'uploads',

    # File access.
    'acl': 'public-read',

    # AWS keys.
    'accessKey': YOUR_AWS_ACCESS_KEY,
    'secretKey': YOUR_AWS_SECRET_KEY
  }
  try:
    response = S3.getHash(config)
  except Exception:
    response = {'error': str(sys.exc_info()[1])}
  return response
<script>
  $.get( '/get_signature', {})
  .done(function( s3Hash ) {
    $('.selector').froalaEditor({
      fileUploadToS3: s3Hash
    })
  });
</script>

Do you think we can improve this article? Let us know.