Apr 11, 2019· 4 mins to read

How to Upload Files in Node/Express Application


How to Upload Files in Node/Express Application

In this article, we will see how to upload files in Node.js Application. How to Upload Files in Node/Express Application

File upload is inevitable in web applications. Every application will have use-case of handling file whether it is user image upload or document upload. it is the most common scenario in the application development

In this article, we will see how to handle the file upload in node.js.

That is to say , There are two ways to store the uploaded file.

  • Uploading file in the system storage. if it is in production, the file will be stored in the server storage
  • we can use cloud provider AWS S3 etc which will store the static files.

we will use express and multer for file upload. so, we need to install the packages.

npm init --yes
npm install --save express multer express-handlebars

express-handlebar is a template engine to render the webpages in the browser. To know more, express-handlebars

screenshot

create a file called server.js and add the following code

const express = require("express");
const exphbs = require("express-handlebars");
const multer = require("multer");
const path = require("path");
const app = express();

/**
 *  Source code for multer configuration
 */
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, path.join(__dirname, "/uploads"));
  },
  filename: function (req, file, cb) {
    console.log("file", file);
    fileExtension = file.originalname.split(".")[1];
    cb(null, file.fieldname + "-" + Date.now() + "." + fileExtension);
  },
});

var upload = multer({ storage: storage });

app.engine("handlebars", exphbs({ defaultLayout: "main" }));

app.set("view engine", "handlebars");

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

app.post("/upload", upload.single("samplefile"), (req, res) => {
  let uploadedfile = req.file.fieldname;

  if (uploadedfile) {
    res.json("file uploaded successfully");
  }
});

const PORT = 3003;

app.listen(PORT, () => {
  console.log(`app is listening to port ${PORT}`);
});

first, we import all the required packages and then we configure the multer to handle the file upload

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, path.join(__dirname, "/uploads"));
  },
  filename: function (req, file, cb) {
    console.log("file", file);
    fileExtension = file.originalname.split(".")[1];
    cb(null, file.fieldname + "-" + Date.now() + "." + fileExtension);
  },
});

multer can be configured in two ways such as adding a destination folder to upload the file and configuring the destination folder and file to handle

multer can handle single file upload and array of files.

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

var app = express();

app.post("/profile", upload.single("avatar"), function (req, res, next) {
  // req.file is the `avatar` file and req.body will hold the text fields, if there were any
});

app.post(
  "/photos/upload",
  upload.array("photos", 12),
  function (req, res, next) {
    // req.files is array of `photos` files
    // req.body will contain the text fields, if there were any
  }
);

var cpUpload = upload.fields([
  { name: "avatar", maxCount: 1 },
  { name: "gallery", maxCount: 8 },
]);
app.post("/cool-profile", cpUpload, function (req, res, next) {
  // req.files is an object (String -> Array) where fieldname is the key, and the value is array of files
  //
  // e.g.
  //  req.files['avatar'][0] -> File
  //  req.files['gallery'] -> Array
  //
  // req.body will contain the text fields, if there were any
});

To Read More about multer :

https://github.com/expressjs/multer#diskstorage

https://github.com/expressjs/multer#singlefieldname

Complete source code : https://repl.it/@ganeshmani/NodeFileUpload

To Learn more about Node.js : https://cloudnweb.dev/category/web-dev/

in short , we have seen How to Upload Files in Node/Express Application

Copyright © Cloudnweb. All rights reserved.