Categories
JavaScript Answers

How to upload images using Node.js, Express, and Mongoose?

Spread the love

To upload images using Node.js, Express, and Mongoose, we use the express.multipart method.

For instance, we write

const express = require("express");
const http = require("http");
const app = express();

app.use(express.static("./public"));
app.use(express.methodOverride());
app.use(
  express.multipart({
    uploadDir: "./uploads",
    keepExtensions: true,
  })
);

app.use(app.router);

app.get("/upload", (req, res) => {
  res.render("upload");
});

app.post("/upload", (req, res) => {
  res.json(req.files);
});

http.createServer(app).listen(3000, () => {
  console.log("App started");
});

to call express.multipart to return a middleware function that accepts uploads.

And then we get the uploaded file from req.files in the /upload route handler.

We use express.static to expose the /public folder as a static file folder.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *