Upload single file API using node js | API development

Published At: 1 year ago
Published By: Santosh Kumar
Downloads: 0
Watch Video
node js mongodb expressjs

1. Step - Setup project

  • Download and install Node js (if you haven't installed).
  • Create an empty project folder.
  • Run command npm init to Initialize the project.
  • Install required packages npm i express mongoose body-parser multer nodemon
  • Create script in package.json file
  • Then run command to start server npm start

 

2. Step - Create a file to set up a server. index.js

This code serves the purpose of setting up a basic web server using Express.js and connecting it to a MongoDB database using Mongoose. 

Import Dependencies: The code starts by importing necessary dependencies:

  • express is a popular Node.js web application framework used for building web applications and APIs.
  • mongoose is an Object Data Modeling (ODM) library for MongoDB, simplifying database interactions.
  • body-parser is a middleware used to parse incoming request bodies. It's needed to handle POST requests with form data.
import express from "express";
import mongoose from "mongoose";
import bodyParser from "body-parser";
import route from "./routes/uploadRoute.js";

const app = express();
app.use(bodyParser.urlencoded({extended:true}));

const PORT = 8000;
// mongodb string url
const URL = "mongodb+srv://youtube:my_youtube@cluster0.iebe8nn.mongodb.net/uploadfile?retryWrites=true&w=majority"

mongoose.connect(URL).then(()=>{

    console.log("DB connected successfully");

    app.listen(PORT, ()=>{
        console.log(`Server is running on port ${PORT}`);
    })

}).catch(error => console.log(error))


app.use("/api/uploads", route);

 

3. Step - Create a model file to make schema uploadModel.js

this code defines a Mongoose schema for handling file upload-related data, including fields for the file name, file path, and file size. It exports a Mongoose model named "Upload" that can be used to interact with a MongoDB collection for storing and querying file upload records.

import mongoose from "mongoose";


const uploadSchema = new mongoose.Schema({
    fileName:{
        type: String,
        required: true,
    },
    filePath:{
        type: String,
        required: true,
    },
    fileSize:{
        type: String,
        required: true,
    }
});

export default mongoose.model("Upload", uploadSchema);

 

4. Step - Create a middleware file to upload image uploadMiddleware.js

this code sets up a multer middleware with custom storage configuration to handle file uploads. It ensures that uploaded files are stored in a directory named "./uploads" and that each file has a unique name to prevent conflicts. The exported multer middleware can be used in other parts of the application to process incoming file uploads.

import multer from "multer";
import fs from "fs";

const storage = multer.diskStorage({
    destination: (req, file, cb) =>{

        const directory = "./uploads";
        // checking if upload directory exist or not if not then create it
        if(!fs.existsSync(directory)){
            fs.mkdirSync(directory);
        }
        cb(null, directory);
    },
    filename: (req, file, cb) =>{
        // create a unique name for uploaded file
        const fileName = `${Date.now()}-${file.originalname}`;
        cb(null,fileName);
    }
})


export default multer({storage});

 

5. Step - Create a controller file to handle logic of upload file data into database uploadController.js 

this code defines a controller function uploadFile for handling file uploads. It extracts file information from the request, saves that information to a MongoDB database using the "Upload" model, and sends an appropriate response based on the success or failure of the process.

import Upload from "../model/uploadModel.js";


export const uploadFile = async(req, res) =>{
    try {

        req.body.fileName = req.file.filename;
        req.body.filePath = req.file.path;
        req.body.fileSize = req.file.size;

        const imageData = await new Upload(req.body);
        const savedImage = await imageData.save();
        res.status(200).json(savedImage);
        
    } catch (error) {
        res.status(500).json({error: error});
    }
}

 

6. Step - Create a route file. uploadRoute.js

this code sets up a POST route for file uploads ("/fileupload") using Express.js. It utilizes the multer middleware for handling file uploads, expecting a file field with the name "myfile." When a file is uploaded to this endpoint, it's first processed by the uploadMiddleware, and then the uploadFile controller function is responsible for saving the file data to the database and responding to the client appropriately.

import express from "express";
import { uploadFile } from "../controller/uploadController.js";
import uploadMiddleware from "../middleware/uploadMiddleware.js";

const route = express.Router();

route.post("/fileupload", uploadMiddleware.single("myfile"), uploadFile);

export default route;