Navigate to index.js file in the root directory to find the complete code.
Clone this repository to your local machine by running the following command in your local system.
git clone https://github.com/aliarslanansari/node_express_aws_s3.git
After cloning change the current directory to this repository folder by running
cd node_express_aws_s3
Then run the following command to install all the packages from packages.json file. Note that yarn or npm must be installed in your system (or install from here Node | Yarn)
npm install
or
yarn install
Create a .env file inside the root directory, and add the following variables to it
AWS_ACCESS_KEY_ID = 'AWSACCESSKEY123'
AWS_SECRET_ACCESS_KEY = 'xyz-aws-secret-access-key'
AWS_SESSION_TOKEN = 'xyz-aws-session_token'
BUCKET_NAME = 'bucket-name-comes-here'
To get your access key ID and secret access key
-
Open the IAM console at https://console.aws.amazon.com/iam/.
-
On the navigation menu, choose Users.
-
Choose your IAM user name (not the check box).
-
Open the Security credentials tab, and then choose Create access key.
-
To see the new access key, choose Show. Your credentials resemble the following:
-
Access key ID: AKIAIOSFODNN7EXAMPLE
-
Secret access key: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
-
For AWS Educate account
-
Go to Vocareum. This is kinda the main page of your student AWS account.
-
Click on the Account Details button.
Also add the BUCKET_NAME as name of the S3 Bucket which you've created from aws console.
After configuring the envronment variabe in .env file, start the server by running the following command in the root directory
If you're using Yarn
yarn start
If you're using NPM
npm start
To test the server is working properly, you'll need to send a post request to upload file to s3, we can test the server using REST client application Postman (you can install Postman from here)
Open Postman and do the following
-
Create a new POST request
-
Add the endpoint URL as below
localhost:3000/upload
-
Navigate to Body and select form-data
-
Enter the key as fileData (we have used same key in the code, line: 30)
-
Select value type as File from the end of Key input field (by default it is Text)
-
Upload file from Value column, click on Select Files
-
After selecting files, Click on Send button
You'll get the following response from the server
{
"message": "File Uploaded Successfully",
"uploaded": 1,
"filesPath": [
"https://bucket-name.s3.amazonaws.com/8dfdsf3-a723-4280-bbd1-7b9c05249720.png"
]
}
If you've set acl:'public-read'
in the object which is passed to multerS3 on line:25 then file can be directly accessed from the URL returned from server in filesPath array.