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.

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

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

Screen Shot 2019 04 11 at 5 26 58 PM

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

1const express = require("express")
2const exphbs = require("express-handlebars")
3const multer = require("multer")
4const path = require("path")
5const app = express()
6
7/**
8 * Source code for multer configuration
9 */
10var storage = multer.diskStorage({
11 destination: function(req, file, cb) {
12 cb(null, path.join(__dirname, "/uploads"))
13 },
14 filename: function(req, file, cb) {
15 console.log("file", file)
16 fileExtension = file.originalname.split(".")[1]
17 cb(null, file.fieldname + "-" + Date.now() + "." + fileExtension)
18 },
19})
20
21var upload = multer({ storage: storage })
22
23app.engine("handlebars", exphbs({ defaultLayout: "main" }))
24
25app.set("view engine", "handlebars")
26
27app.get("/", (req, res) => {
28 res.render("home")
29})
30
31app.post("/upload", upload.single("samplefile"), (req, res) => {
32 let uploadedfile = req.file.fieldname
33
34 if (uploadedfile) {
35 res.json("file uploaded successfully")
36 }
37})
38
39const PORT = 3003
40
41app.listen(PORT, () => {
42 console.log(`app is listening to port ${PORT}`)
43})

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

1var storage = multer.diskStorage({
2 destination: function(req, file, cb) {
3 cb(null, path.join(__dirname, "/uploads"))
4 },
5 filename: function(req, file, cb) {
6 console.log("file", file)
7 fileExtension = file.originalname.split(".")[1]
8 cb(null, file.fieldname + "-" + Date.now() + "." + fileExtension)
9 },
10})

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.

1var express = require("express")
2var multer = require("multer")
3var upload = multer({ dest: "uploads/" })
4
5var app = express()
6
7app.post("/profile", upload.single("avatar"), function(req, res, next) {
8 // req.file is the `avatar` file and req.body will hold the text fields, if there were any
9})
10
11app.post("/photos/upload", upload.array("photos", 12), function(
12 req,
13 res,
14 next
15) {
16 // req.files is array of `photos` files
17 // req.body will contain the text fields, if there were any
18})
19
20var cpUpload = upload.fields([
21 { name: "avatar", maxCount: 1 },
22 { name: "gallery", maxCount: 8 },
23])
24app.post("/cool-profile", cpUpload, function(req, res, next) {
25 // req.files is an object (String -> Array) where fieldname is the key, and the value is array of files
26 //
27 // e.g.
28 // req.files['avatar'][0] -> File
29 // req.files['gallery'] -> Array
30 //
31 // req.body will contain the text fields, if there were any
32})

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

To Read More

Kubernetes for Nodejs developers

Do you keep hearing the word kubernetes in the tech community and you couldn't u...

TypeScript Interfaces vs Types

In this article, we will see what are interfaces and types and the difference be...

How to find project ideas to practi...

Ever wondered what how to get a real world experience on web development while w...

Building a Production-grade Nodejs,...

This article is the first part of building a production grade nodejs,graphql and...

Modern React Redux Tutorials with R...

This tutorial explain how you can build an application using modern react redux ...

Building a Piano with React Hooks

In this article, we will see how to build a piano with react hooks. Building a P...

TypeScript Basics - The Definitive ...

In this article, we will learn some basics of typescript which helps you to deve...

Here's why podman is more secured t...

In this article we will see about podman and why it is more secured way to run c...

What is gRPC ? How to implement gRP...

Everyone talks about gRPC. Have you ever wonder how it works or how to implement...