NodeJS Upload Files

Learn how to upload files in NodeJS
Learn how to upload files in NodeJS

NodeJS is a popular server-side platform that provides various modules for performing common tasks. One of the essential modules for web development is the “fs” (File System) module, which provides a way to interact with the file system on the server. Another module, the “http” module, provides a way to handle incoming HTTP requests and send HTTP responses. In this article, we’ll explore the techniques to upload files from a client to the server using NodeJS.NodeJS is a popular server-side platform that offers a variety of modules for completing basic tasks.

The “fs” (File System) module, which allows you to communicate with the server’s file system, is one of the most important modules for web development. Another module, the “http” module, handles incoming HTTP requests and sends HTTP answers. In this tutorial, we’ll look at how to use NodeJS to upload files from a client to the server.

Creating an HTML form for file upload

To upload files from a client to a server, we must first develop an HTML form with a file input box. The form should be sent to the server through the POST method, which includes the data in the request body. Here’s an example of an HTML file upload form:

<form action="http://localhost:3000/upload" method="post" enctype="multipart/form-data">
  <input type="file" name="myFile">
  <input type="submit" value="Upload">
</form>

In this example, the form is submitted to the URL “http://localhost:3000/upload” using the POST method. The enctype attribute is set to “multipart/form-data”, which is the default encoding type for file upload. The file input field has a name “myFile”, which is used to access the uploaded file in the NodeJS code.

Handling file uploads with NodeJS

To manage file uploads using NodeJS, we must first build a server that listens for incoming POST requests and processes the files that are uploaded. We may use the “http” module and its “createServer” function to create the server. An example of a NodeJS server that processes file uploads is shown below:

const http = require("http");
const fs = require("fs");
const port = 3000;

const server = http.createServer((req, res) => {
  if (req.url === "/upload" && req.method === "POST") {
    let body = "";
    req.on("data", chunk => {
      body += chunk;
    });
    req.on("end", () => {
      fs.writeFile("myFile.txt", body, err => {
        if (err) {
          res.statusCode = 500;
          res.end("Error: " + err.message);
        } else {
          res.statusCode = 200;
          res.end("File uploaded");
        }
      });
    });
  } else {
    res.statusCode = 404;
    res.end("Not found");
  }
});

server.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});

The server in this example listens on port 3000 and constructs a handler function that is run for each incoming request. If the URL is “/upload” and the method is POST, the handler function gets the data from the request body and writes it to the file “myFile.txt”. If the write operation is successful, a response with the status code 200 and the message “File uploaded” is sent. If an error occurs, it returns a response with the status code 500 and the error message.

Q&A

Q: What is the difference between POST and GET?
A: POST and GET are two HTTP methods used to send data to a server. The main difference between them is the way they send data. GET appends the data to the URL as query parameters, while POST sends the data in the request body. In general, GET is used for retrieval of data from a server, while POST is used for sending data to the server.

Exercises

  1. Modify the code to handle multiple file uploads and store them in separate files.
  2. Add a validation to the code to check the file size and type before uploading.
  3. Add a progress bar to display the upload progress to the user.

Answers

You may use a for loop to process each file in the request body to manage multiple file uploads. The files may be accessed using the “multer” package, which allows you to manage multi-part form data. Here’s an example of how to use the “multer” library to manage multiple file uploads:

const multer = require("multer");
const upload = multer({ dest: "uploads/" });

app.post("/upload", upload.array("myFiles"), (req, res) => {
  req.files.forEach(file => {
    fs.writeFile(file.originalname, file.buffer, err => {
      if (err) {
        console.error(err.message);
      }
    });
  });
  res.send("Files uploaded");
});

To add validation to the code, use the “limits” option of the “multer” library to define the file size and type. Here’s an example of how to use the “multer” library to validate the file size and type:

const multer = require("multer");
const upload = multer({
  dest: "uploads/",
  limits: {
    fileSize: 1024 * 1024 * 5,
    fileFilter: (req, file, cb) => {
      if (file.mimetype === "image/jpeg" || file.mimetype === "image/png") {
        cb(null, true);
      } else {
        cb(new Error("Invalid file type"));
      }
    }
  }
});

app.post("/upload", upload.array("myFiles"), (req, res) => {
  req.files.forEach(file => {
    fs.writeFile(file.originalname, file.buffer, err => {
      if (err) {
        console.error(err.message);
      }
    });
  });
  res.send("Files uploaded");
});

You may use the “socket.io” package to deliver progress updates from the server to the client to create a progress bar. Here’s an example of how to use the “socket.io” library to create a progress bar:

const multer = require("multer");
const upload = multer({ dest: "uploads/" });
const app = require("express")();
const server = require("http").Server(app);
const io = require("socket.io")(server);

app.post("/upload", upload.array("myFiles"), (req, res) => {
  io.on("connection", socket =>
Scroll to Top