LoginSignup
1
0

More than 5 years have passed since last update.

Upload image to S3 using Javascript AWS SDK

Posted at

Getting started

Install aws-sdk using npm

$ npm install aws-sdk

Create a json file name config.json in the project root directory

{
    "accessKeyId": "<aws-access-key>", 
    "secretAccessKey": "<aws-secret-key>", 
    "region": "ap-northeast-1"
}

Usage

Import the aws-sdk

const AWS = require('aws-sdk')

Initialize S3 object for doing the operations

// load aws s3 configuration from json file
AWS.config.loadFromPath(path.join(__dirname, '<relative-path-to-config.json>'))

// initialize S3 object for doing operations
var S3 = new AWS.S3({
   apiVersion: '2006-03-01'
})
  • Get image from S3
// setup the params for get object operation
var params = {
  Bucket: <path-to-where-the-target-object-is-stored>
  Key: <object-name-in-s3>
}

// Async function to get object from S3 using aws-sdk
S3.getObject(params, function (err, data) {
  if (err) throw err
  console.log(data)
})
.catch(err => console.log(err))
  • Upload Image to S3
// setup the params for get object operation
var params = {
  Bucket: "bucket name with path",
  Key: "<filename>",
  Body: "<image stream>"
}

// Async function to get object from S3 using aws-sdk
S3.getObject(params, function (err, data) {
  if (err) throw err
  console.log(data)
})
.catch(err => console.log(err))
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0