Navigation

AWS S3 Snippets

The code snippets on this page demonstrate how to work with Amazon Simple Storage Service through the AWS Service. All of the snippets require an AWS Service interface with rules that allow the service actions used in the snippet and are intended to be used within a Stitch function.

If your app does not have an AWS Service interface, create one before using these snippets.

Upload an Image to S3

This Stitch function uploads a Base64 encoded image to AWS S3 using the PutObject action.

exports = function(base64EncodedImage, bucket, fileName, fileType) {
  // Convert the base64 encoded image string to a BSON Binary object
  const binaryImageData = BSON.Binary.fromBase64(base64EncodedImage, 0);
  // Instantiate an S3 service client
  const s3Service = context.services.get('myS3Service').s3('us-east-1');
  // Put the object to S3
  return s3Service.PutObject({
    'Bucket': bucket,
    'Key': fileName,
    'ContentType': fileType,
    'Body': binaryImageData
  })
  .then(putObjectOutput => {
    console.log(putObjectOutput);
    // putObjectOutput: {
    //   ETag: <string>, // The object's S3 entity tag
    // }
    return putObjectOutput
  })
  .catch(console.error);
};

Function Parameters

Parameter Type Description
base64EncodedImage string A Base64 encoded image. You can convert an image File to Base64 with the readAsDataURL method from the FileReader Web API.
bucket string The name of the S3 bucket that will hold the image.
fileName string The name of the image file, including its file extension.
fileType string The MIME Type of the image.

Get an Image From S3

This Stitch function retrieves an object from AWS S3 using the GetObject action.

exports = function(bucket, fileName) {
  // Instantiate an S3 service client
  const s3Service = context.services.get('myS3Service').s3('us-east-1');
  // Get the object from S3
  return s3Service.GetObject({
    'Bucket': bucket,
    'Key': fileName,
  })
  .then(getObjectOutput => {
    console.log(getObjectOutput);
    // {
    //   ETag: <string>, // The object's S3 entity tag
    //   Body: <binary>, // The object data
    //   ContentType: <string>, // The object's MIME type
    // }
    const base64EncodedImage = getObjectOutput.Body
    return base64EncodedImage
  })
  .catch(console.error);
};

Function Parameters

Parameter Type Description
bucket string The name of the S3 bucket that will hold the image.
fileName string The name of the image file, including its file extension.