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.
we will use express and multer for file upload. so, we need to install the packages.
1npm init --yes2npm install --save express multer express-handlebars
express-handlebar is a template engine to render the webpages in the browser. To know more, express-handlebars
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()67/**8 * Source code for multer configuration9 */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})2021var upload = multer({ storage: storage })2223app.engine("handlebars", exphbs({ defaultLayout: "main" }))2425app.set("view engine", "handlebars")2627app.get("/", (req, res) => {28 res.render("home")29})3031app.post("/upload", upload.single("samplefile"), (req, res) => {32 let uploadedfile = req.file.fieldname3334 if (uploadedfile) {35 res.json("file uploaded successfully")36 }37})3839const PORT = 30034041app.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/" })45var app = express()67app.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 any9})1011app.post("/photos/upload", upload.array("photos", 12), function(12 req,13 res,14 next15) {16 // req.files is array of `photos` files17 // req.body will contain the text fields, if there were any18})1920var 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 files26 //27 // e.g.28 // req.files['avatar'][0] -> File29 // req.files['gallery'] -> Array30 //31 // req.body will contain the text fields, if there were any32})
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
No spam, ever. Unsubscribe anytime.