DEV Community

Apexx Cloud
Apexx Cloud

Posted on

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

Top comments (1)

Collapse
 
vikzzrhino profile image
VikzzRhino

Apexx Cloud has turned my file management headaches into a distant memory. Uploads, transformations, CDN delivery it's like magic, but real. If you're not using it yet, are you even developing, or just struggling for sport?