Skip to main content

How to Upload Files in Node/Express Application

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 destinationfolder 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 :

Comments

Popular posts from this blog

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...