In our case we are going to work with only two files controllers/index.js and
views/index.html

Next, you need the AWS SDK. It is just one line to install with NPM.

$ npm install aws-sdk --save

Signing Securely S3 Uploads

With your current configuration S3 will not allow uploading of files unless
they are authenticated.

For this purpose we need to use a temporary signed URL for each file upload to S3.

Let’s see how your controller at controller/index.js should look like.

varexpress=require('express'),router=express.Router(),aws=require('aws-sdk')router.get('/',function(req,res){res.render('index')})varAWS_ACCESS_KEY='your_AWS_access_key'varAWS_SECRET_KEY='your_AWS_secret_key'varS3_BUCKET='images_upload'router.get('/sign',function(req,res){aws.config.update({accessKeyId:AWS_ACCESS_KEY,secretAccessKey:AWS_SECRET_KEY});vars3=newaws.S3()varoptions={Bucket:S3_BUCKET,Key:req.query.file_name,Expires:60,ContentType:req.query.file_type,ACL:'public-read'}s3.getSignedUrl('putObject',options,function(err,data){if(err)returnres.send('Error with S3')res.json({signed_request:data,url:'https://s3.amazonaws.com/'+S3_BUCKET+'/'+req.query.file_name})})})module.exports=router

Let’s look what we have hear.

There are two request handlers. The first renders our page, which we will look
at in a minute.

The second handler uses the AWS SDK to request that S3 generates a temporary URL where
you can upload your file. This URL is valid only for 60 seconds, as per the Expires
option.

Once the request is successfully returned you send back the generated URL.

First at the beginning of the page we have a simple file field which the user
can use to choose a file.

The more interesting part is in the JavaScript section at the bottom of the page.
First, we listen to the change event of the file field with onchange which is
fired when the user selects a file.

When fired we use the sign_request function to get a signed temporary URL
where the browser can upload the file. Then again using AJAX you upload the file
with the upload function to the temporary URL.

Once the file is uploaded we display it to the user.

This is everything that you have to do. As you can see the file never reaches
your server. Only tiny little bit of data is actually handle by it. Almost the
entire workload is handled by S3.

Don’t forget, S3 is great not only for uploading and storing files, but it is
also very capable of serving files. It can easily server files of all sizes to
millions of users simultaneously.

Next

As you can see it is very simple to upload files directly to S3. However, sometimes
you need first to process a file before uploading to a server. This is what you can
try to do next.

Did you like this article?

Please share it

Enter your email and get our NPM Cheat Sheet for NodeJS Developers and
the links to our 5 most popular articles which have helped thousands of
developers build faster, more reliable and easier to maintain Node applications.