S3 or Simple Storage Service is a cloud based storage service offered by Amazon. We can use amazon s3 to store files of different formats and later on we can access them easily when needed. In this tutorial we'll learn how to use Node.js to upload a file to Amazon s3 service. Don't worry if you don't have a s3 bucket , we'll walk you through the steps of creating your s3 bucket. Let's get started!
Step - 1 : After signing in , go to the storage domain and click on s3 as shown in
image below :
Just like any other npm package we can install aws-sdk using the following command:
npm install aws-sdk
In this case , we are giving the data to the s3 in the form of content in the body as shown below :
var AWS = require('aws-sdk');
var s3 = new AWS.S3();
// Bucket names must be unique across all S3 users
var myBucket = 'njera';
var myKey = 'textFile';
params = {Bucket: myBucket, Key: myKey, Body: 'Valueeee or some data' };
s3.putObject(params, function(err, data) {
if (err) {
console.log(err)
} else {
console.log("Successfully uploaded data to myBucket/myKey");
}
});
in this case , we can provide any type of file and fs will read and upload it on the s3.
var AWS = require('aws-sdk');
var fs = require('fs');
var s3 = new AWS.S3();
// Bucket names must be unique across all S3 users
var myBucket = 'njera';
var myKey = 'jpeg';
//for text file
//fs.readFile('demo.txt', function (err, data) {
//for Video file
//fs.readFile('demo.avi', function (err, data) {
//for image file
fs.readFile('demo.jpg', function (err, data) {
if (err) { throw err; }
params = {Bucket: myBucket, Key: myKey, Body: data };
s3.putObject(params, function(err, data) {
if (err) {
console.log(err)
} else {
console.log("Successfully uploaded data to myBucket/myKey");
}
});
});