How to Upload File to Cloudfront Bucket

Most applications today serve users beyond the earth and need a way to deliver their content fast. To attain this, developers often rely on a Content Commitment Network (CDN), a network of servers that are geographically distributed with the intent of serving content to users as fast every bit possible.

Amazon CloudFront is ane such CDN. In this article, I will describe how to upload files to S3 bucket and serve those files through CloudFront in Node.js.

Prerequisites

Create a bucket in S3 and create a CloudFront distribution in AWS. Navigate to IAM and go to Security Credentials under User. Create an admission key and download the CSV file. We will demand this access key later.

And then, click on My Security Credentials in My Account.

My security credentials

Under CloudFront central pairs, create a key-pair and download the private cardinal. Make certain to proceed track of your admission key ID. Nosotros will need information technology later for integration.

Creating Node.js Application

Let'due south create a elementary Node.js express server and add two REST API endpoints for file upload and download. Here is the sample project structure.

I am using typescript and ts-node-dev npm modules in this sample projection. Therefore, I have tsconfig.json in the project.

Here is the entire app.ts file. The file contains the logic to initialize express server and Residual endpoints. I am likewise using a multernpm module to handle multi-part file upload.

          import express from 'limited'; import * as fileCtrl from './fileController'; import multer from 'multer'; import crypto from 'crypto'; import path from 'path';  const app = express(); const port = 3000;  app.mind(port, () => {   console.log('Server listening on port %due south.', port); });  //Multer module for treatment multi part file upload. var storage = multer.diskStorage({   destination: './files',   filename: office (req, file, cb) {     crypto.pseudoRandomBytes(16, role (err, raw) {       if (err) render cb(err)        cb(aught, raw.toString('hex') + path.extname(file.originalname))     })   } })  app.use(multer({ storage: storage }).single('file'));   app.get('/api/download', asyncHandler(fileCtrl.download)); app.post('/api/upload', asyncHandler(fileCtrl.upload));  export part asyncHandler(handler) {   render function (req, res, next) {     if (!handler) {       adjacent(new Error(`Invalid handler ${handler}, it must exist a function.`));     } else {       handler(req, res, next).grab(next);     }   }; }        

Uploading Files to Amazon S3 Bucket

Let usa expect at how to upload files to S3 saucepan. We volition need to install node moduleaws-sdkto access S3 buckets from Node.js application.

In one case we have installed the handler for upload, the endpoint is defined in as follows:

          export async role upload(req, res) {   let response = await uploadFile(req.file.originalname, req.file.path);   res.ship(response);   res.terminate(); }        

In fileComponent.ts,we demand to import the AWS-SDK module every bit follows.

          import awsSDK from 'aws-sdk';        

In the get-go of this commodity, we downloaded a CSV file that contained admission key id and secret admission key. We will apply them to upload files to the S3 saucepan. Using the AWS-SDKmodule, nosotros need to configure the admission key id and clandestine access fundamental equally follows:

          export function uploadFile(filename, fileDirectoryPath) {   awsSDK.config.update({ accessKeyId: procedure.env.S3_ACCESS_KEY_ID, secretAccessKey: process.env.S3_SECRET_ACCESS_KEY });   const s3 = new awsSDK.S3();    render new Promise(part (resolve, reject) {     fs.readFile(fileDirectoryPath.toString(), office (err, data) {       if (err) { reject(err); }       s3.putObject({         Bucket: '' + process.env.S3_BUCKET_NAME,         Central: filename,         Body: data,         ACL: 'public-read'       }, role (err, information) {         if (err) refuse(err);         resolve("succesfully uploaded");       });     });   }); }        

Using the putObject() method, we will upload files to the S3 bucket. In putObject(), we need to pass the saucepan name to which nosotros will upload the files. Note that, depending on your bucket policies, y'all can send parameters in putObject().In this example, I take set the canned ACL policy topublic-read.

Now, we can start the server and test our Post endpoint. Here is an example from Postman.

Postman

In one case the request is successful, we can come across the file in the S3 bucket.

S3 bucket

Serving Files via Amazon CloudFront

Earlier, we downloaded private key from CloudFront key pairs. We will use that individual key and access primal ID to access CloudFront in Node.js.

The handler for download API endpoint is as follows.

          export async function download(req, res) {   permit response = await getFileLink(req.query.filename);   res.send(response);   res.end(); }        

In this handler, nosotros are expecting a file proper noun that has to be downloaded via CloudFront.

Let us look at how to admission CloudFront in our Node.js app. First, we will install an aws-cloudfront-signnpm module. Using this module, we can get signed Amazon CloudFront URLs which enables us to provide users access to our private content. The signed URLs besides comprise additional meta-information, such as expiration time. This gives more control over access to our content.

          export function getFileLink(filename) {   render new Hope(part (resolve, reject) {     var options = { keypairId: procedure.env.CLOUDFRONT_ACCESS_KEY_ID, privateKeyPath: procedure.env.CLOUDFRONT_PRIVATE_KEY_PATH };     var signedUrl = awsCloudFront.getSignedUrl(process.env.CLOUDFRONT_URL + filename, options);     resolve(signedUrl);   }); }        

Hither, we need to pass the access key ID path to the private key file and CloudFront URL to getSignedUrl(). The CloudFront URL should look something like this: https://XYZ.cloudfront.net .

Start the server and test the GET endpoint as follows:

GET endpoint

Conclusion

In this article, nosotros saw how to upload files to Amazon S3 and serve those files via Amazon CloudFront. I promise yous enjoyed this article. Let me know if you have any comments or suggestions in the comments section below.

The example for this article can be constitute on this GitHub repository.

Opinions expressed past DZone contributors are their own.

payneyoundither.blogspot.com

Source: https://dzone.com/articles/how-to-upload-and-serve-data-using-amazon-couldfro

0 Response to "How to Upload File to Cloudfront Bucket"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel