Logo

dev-resources.site

for different kinds of informations.

How to implement File uploads in Nodejs: A step by step guide

Published at
1/2/2025
Categories
webdev
javascript
s3
express
Author
apexx_cloud
Categories
4 categories in total
webdev
open
javascript
open
s3
open
express
open
Author
11 person written this
apexx_cloud
open
How to implement File uploads in Nodejs: A step by step guide

Introduction

Hi, In this article we will see how to handle file uploads in a nodejs server and storing it with best practices. I will be using Apexx cloud as our file storage service.

Install the packages

npm i express nodemon cors multer @apexxcloud/sdk-node dotenv
Enter fullscreen mode Exit fullscreen mode

Once installed, update your package.json to add the start script

"scripts":{
 "start": "nodemon index.js",
 // rest of the scripts
}
Enter fullscreen mode Exit fullscreen mode

Create a index.js file in the root folder, then create a folder called src. In the src folder create the folders for controllers and routes respectively, Your folder structure should look something like this.

project-root/
ā”‚
ā”œā”€ā”€ index.js              # Entry point of the application
ā”œā”€ā”€ package.json          # Project metadata and dependencies
ā”œā”€ā”€ package-lock.json     # Auto-generated dependency tree
ā”œā”€ā”€ node_modules/         # Installed dependencies
ā”‚
ā””ā”€ā”€ src/
    ā”œā”€ā”€ controllers/      # Contains controller files
    ā”‚   ā””ā”€ā”€ file.controller.js
    ā”‚
    ā”œā”€ā”€ routes/           # Contains route files
    ā”‚   ā””ā”€ā”€ file.route.js

Enter fullscreen mode Exit fullscreen mode

Setup Apexx cloud

  1. Login to Apexx cloud or create a new account here

  2. Navigate to buckets.

  3. Click on "Create bucket" and provide a unique name for your bucket.

  4. Select the desired region

  5. Review and create the bucket

  6. Navigate to Api keys

  7. Click on "Create API Key" and provide a name for your key

  8. Review and create the key

  9. Copy your secret key and store it somewhere securely.

  10. Then copy your access key as well.

Lets start writing some code

Lets start writing our controller that will handle the request in file.controller.js.

// Setup our apexx cloud sdk
const ApexxCloud = require("@apexxcloud/sdk-node");
const storage = new ApexxCloud({
  accessKey: process.env.APEXXCLOUD_ACCESS_KEY,
  secretKey: process.env.APEXXCLOUD_SECRET_KEY,
  region: process.env.APEXXCLOUD_REGION,
  bucket: process.env.APEXXCLOUD_BUCKET,
});

// Upload file function
const uploadFile = async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({ error: "No file provided" });
    }
    const { originalname, filename, size, path, mimetype } = req.file;

    const { key, visibility } = req.query;

    const result = await storage.files.upload(req.file.buffer, {
      key: key || orginalname,
      visibility: visiblity || "public",
      contentType: mimetype,
    });

    res.status(200).json(result);
  } catch (error) {
    console.log(error);
    res.status(500).json({ error: `File upload failed: ${error.message}` });
  }
};
Enter fullscreen mode Exit fullscreen mode

First we are importing @apexxcloud/sdk-node and we are creating a storage object by passing in the credentials. Then we are creating the function called uploadFile, In the function we are getting the key and visibility from req.query and file details from req.file

Then we are using the upload function from the apexx cloud sdk to upload it to apexx cloud. When uploading you can configure the visibility of the file, It can be public or private, All the files are public by default.

Now lets setup the routes in file.route.js.

const express = require("express");
const router = express.Router();
const multer = require("multer");
const { uploadFile } = require("../controllers/file.controller")

// setup multer
const upload = multer({ storage: multer.memoryStorage() });

// setup the route
router.post("/upload", upload.single("file"), uploadFile);

// export the router
module.exports = router
Enter fullscreen mode Exit fullscreen mode

Then lets setup the index.js file.

const express = require("express");
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const cors = require("cors");

// load env variables
dotenv.config();

// import file route
const fileRoute = require("./src/routes/file.route");

// setup express
const app = express();

app.use(express.urlencoded({ extended: true, limit: "100mb" }));
app.use(express.json({ limit: "100mb" }));
app.use(cors());

// setup the file route
app.use(fileRoutes);

const port = 8000
app.listen(port, () => {
  console.log(`Server running at port:${port}`);
});

Enter fullscreen mode Exit fullscreen mode

Open your terminal and run:

npm start, If everything went right, it should log "Server running at port:8000".

Testing the API

We'll test the API using postman.

Apexx cloud

Select Body, check form-data, add a key called file and set the type to file. Upload your file then click send.

You should get a response as below:

{
    "data": {
        "message": "File uploaded successfully",
        "key": "file.png",
        "location": "https://cdn.apexxcloud.com/f/ojGnBqCLkTnI/file.png",
        "bucket": "your-bucket-name",
        "region": "WNAM",
        "visibility": "private",
        "size": 14513,
        "content_type": "image/png"
    }
}
Enter fullscreen mode Exit fullscreen mode

Indicating that the file has been uploaded. Go to your Apexx Cloud dashboard, Then go to your bucket, you shoud see the file you uploaded there.

And that's it, you have successfully implemented file uploads in nodejs and the best part is Apexx Cloud provides you with on the fly transformations and a superfast CDN for free. To know more go here, for the documentation go here.

Conclusion

This article has successfully taught you how to handle file uploads in a nodejs application using Apexx Cloud and Multer.

In the next article I will show how to use AWS S3 for file uploads, until then Signing Off - Your's FII

Never worry about file uploads: Sign up for Apexx Cloud Today, It's Free

s3 Article's
30 articles in total
Favicon
Building a Weather Data Collection System with AWS S3 and OpenWeather API
Favicon
Comprehensive Guide to Installing AWS CLI, Configuring It, and Downloading S3 Buckets Locally
Favicon
Stream de Arquivo PDF ou Imagem S3 - AWS
Favicon
Efficiently Deleting Millions of Objects in Amazon S3 Using Lifecycle Policy
Favicon
Uploading Files to Amazon S3 in ASP.NET Core with Razor Pages
Favicon
AWS S3 Presigned URLs: Secure and Temporary File Access Made Simple
Favicon
How to implement File uploads in Nodejs: A step by step guide
Favicon
Lee esto antes de implementar S3 y CloudFront usando Terraform.
Favicon
Lee esto antes de implementar S3 y CloudFront usando Terraform.
Favicon
šŸš€ 1. Efficient Video Uploads to AWS S3 with React
Favicon
Full Stack Application Hosting in AWS
Favicon
Building an S3 Static Website with CloudFront Using Terraform
Favicon
Configure IRSA using EKS to access S3 from a POD in terraform
Favicon
Setting up IAM Anywhere using terraform
Favicon
AWS S3 System Design Concepts
Favicon
Creating an S3 Bucket in AWS and generate a pre - signed URL
Favicon
Switching to the Terraform S3 Backend with Native State File Locks
Favicon
Around the World in 15 Buckets
Favicon
My (non-AI) AWS re:Invent 24 picks
Favicon
How to Simulate AWS S3 on Your Local Machine with LocalStack
Favicon
Building Websites with Cursor and AWS.
Favicon
Configuring AWS WAF, CloudFront, and S3 Bucket for Secure Access
Favicon
Buckets? No, S3 buckets
Favicon
Download Video from s3 with Cloudfront, nodejs and react
Favicon
AWS Quick Guide - Amazon S3
Favicon
Fastest and Cheapest Ways to Delete Millions of Files from Amazon S3
Favicon
Using MinIO Server for Local Development: A Smarter Alternative to S3
Favicon
AWS CloudFront vs S3 Cross-Region Replication
Favicon
Comparison of S3 upload feature between Documenso and aws-s3-image-upload example
Favicon
Securing Your AWS EC2 and S3 Communication: Best Practices for Enhanced Security

Featured ones: