Home > Web Front-end > JS Tutorial > How to implement File uploads in Nodejs: A step by step guide

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

Patricia Arquette
Release: 2025-01-03 01:36:39
Original
866 people have browsed it

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
Copy after login

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

"scripts":{
 "start": "nodemon index.js",
 // rest of the scripts
}
Copy after login

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

Copy after login

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}` });
  }
};
Copy after login

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
Copy after login

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}`);
});

Copy after login

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.

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

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",
        "bucket": "your-bucket-name",
        "region": "WNAM",
        "visibility": "private",
        "size": 14513,
        "content_type": "image/png"
    }
}
Copy after login

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

The above is the detailed content of How to implement File uploads in Nodejs: A step by step guide. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template