Node.js Express Upload Image to Database Example

This blog will demonstrate implementation of how to use node js and multer to upload unmarried/multiple files on local server.

Introduction

Whenever y'all make a website like social media app or weblog app , y'all volition most probably have feature where y'all will allow user to upload images. That'due south what nosotros volition build here — minimal file upload server.


What are nosotros building?

We are going to build a simple application using node.js which is capable of uploading sinlge/multiple images to server.

There are various ways by which we tin can upload epitome to server using node.js. One of the easiest and common ways to do information technology is by using multer library.

Multer is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files.


Final project Structure

For reference hither is theconcluding projection structure you will acceptafter completing this commodity.

Image for post

Setup

1. Outset open up cmd and run the post-obit control to check if you lot accept node installed. If yous don't have it installed follow this article to install node.js.

          node -v        

2. Create a project directory and cd into it

          mkdir file-upload-app cd file-upload-app        

Lets begin with the lawmaking:

1. Run npm init to starting time create package.json.

          npm init -y        

2. Install express

          npm install express        

three. Install multer

          npm install multer        

four. Create a folder named public in root directory. Here we volition later place our html files.Also create a uploads folder.

v. At present lets create a html folio which contains 2 simple forms.

  • To upload single epitome
          <form method="POST" action="/profile-upload-unmarried" enctype="multipart/form-data">     <div>         <characterization>Upload profile picture</label>         <input blazon="file" name="profile-file" required/>     </div>     <div>         <input type="submit" value="Upload" />     </div> </class>        

Single image upload form of index.html

  • To upload multiple images
          <form method="Postal service" action="/profile-upload-multiple" enctype="multipart/grade-information">     <div>         <characterization>Upload multiple profile picture show</label>         <input blazon="file" proper name="contour-files" required multiple  />     </div>     <div>         <input blazon="submit" value="Upload" />     </div> </form>        

Multiple prototype upload form of index.html

six. Final html file (public/alphabetize.html) volition look like.

index.html

          <!DOCTYPE html> <head>     <title>Profile form</title> </head> <trunk>     <form method="POST" action="/profile-upload-unmarried" enctype="multipart/form-data">         <div>             <label>Upload profile movie</characterization>             <input blazon="file" name="profile-file" required/>         </div>         <div>             <input type="submit" value="Upload" />         </div>     </form>      <hr>      <form method="POST" action="/contour-upload-multiple" enctype="multipart/form-data">         <div>             <characterization>Upload multiple profile picture</label>             <input type="file" name="profile-files" required multiple  />         </div>         <div>             <input type="submit" value="Upload" />         </div>     </form> </body> </html>        

7. Create alphabetize.js in current root projection directory.

8. Import express,multer and initialize port variable to 3000.

          var express = require('limited') var multer  = crave('multer') var app = express() var port = 3000;        

9. Nosotros need to tell multer where we want to upload images and past what proper name should the file be saved. For that we create a object as

          var storage = multer.diskStorage({     destination: function (req, file, cb) {       cb(null, './uploads')     },     filename: function (req, file, cb) {       cb(null, file.originalname)     } }) var upload = multer({ storage: storage })        

This will set epitome upload destination to "uploads" folder and filename will exist same as uploaded file'southward original name.

10. To understand upcoming code lets consider a general example and understand it.

          // General Example app.apply('/a',express.static('/b'));  // Above line would serve all files/folders inside of the 'b' directory // And make them accessible through http://localhost:3000/a.        

We want to upload image, then shop it to a "uploads" directory and make image attainable on web page.

          app.apply(express.static(__dirname + '/public')); app.use('/uploads', express.static('uploads'));        

Then now when nosotros upload image (lets say sample.png) information technology volition be stored uploads folder and will be accessible on spider web page on the url http://localhost:3000/uploads/sample.png

11. Route to upload single image

          app.post('/contour-upload-single', upload.single('profile-file'), role (req, res, next) {   // req.file is the `profile-file` file   // req.body volition hold the text fields, if in that location were whatsoever   console.log(JSON.stringify(req.file))   var response = '<a href="/">Home</a><br>'   response += "Files uploaded successfully.<br>"   response += `<img src="${req.file.path}" /><br>`   return res.send(response) })        

12. Route to upload multiple images

          app.postal service('/profile-upload-multiple', upload.assortment('profile-files', 12), function (req, res, next) {     // req.files is assortment of `profile-files` files     // req.body will contain the text fields, if there were any     var response = '<a href="/">Home</a><br>'     response += "Files uploaded successfully.<br>"     for(var i=0;i<req.files.length;i++){         response += `<img src="${req.files[i].path}" /><br>`     }          return res.transport(response) })        

Lets look at the entire code at once now

index.js

          var express = require('express') var multer  = require('multer') var port = 3000;  var app = express()  var storage = multer.diskStorage({     destination: function (req, file, cb) {       cb(null, './uploads')     },     filename: function (req, file, cb) {       cb(naught, file.originalname)     } }) var upload = multer({ storage: storage })  /* app.use('/a',express.static('/b')); Above line would serve all files/folders inside of the 'b' directory And make them attainable through http://localhost:3000/a. */ app.apply(express.static(__dirname + '/public')); app.utilise('/uploads', express.static('uploads'));  app.mail service('/profile-upload-unmarried', upload.unmarried('contour-file'), office (req, res, next) {   // req.file is the `profile-file` file   // req.body will concur the text fields, if there were whatever   console.log(JSON.stringify(req.file))   var response = '<a href="/">Habitation</a><br>'   response += "Files uploaded successfully.<br>"   response += `<img src="${req.file.path}" /><br>`   return res.send(response) })  app.post('/profile-upload-multiple', upload.array('profile-files', 12), function (req, res, side by side) {     // req.files is array of `profile-files` files     // req.body volition contain the text fields, if at that place were any     var response = '<a href="/">Habitation</a><br>'     response += "Files uploaded successfully.<br>"     for(var i=0;i<req.files.length;i++){         response += `<img src="${req.files[i].path}" /><br>`     }          return res.send(response) })      app.listen(port,() => console.log(`Server running on port ${port}!`))        

Time to see the results

Open the concluding and cd to electric current project directory and enter

          node index.js        

Visit http://localhost:3000/

Output:

Initial view:

Image for post

Before clicking upload:

Image for post

Output (Single image upload):

You will get the following success message and image volition be uploaded to "uploads" folder in projection root directory

Image for post

Output (Multiple image upload):

Uploaded two random images for testing.

Image for post

To bank check if our server actually worked checkout uploads folder in root directory.

Image for post

As yous can see that the images we take uploaded are saved in "uploads" binder.

That's all ! At present nosotros have a website which is capable of uploading single/multiple images to server.

To know about more than options similar restricting file size, accepting files with specific extensions only etc checkout multer.

Decision

So we have successfully built a website containing forms to upload single / multiple images using multer library.

For code you lot tin visit https://github.com/RugvedB/Nodejs-Multer-File

spenceroncoure.blogspot.com

Source: https://www.gyaanibuddy.com/blog/how-to-upload-image-using-multer-in-nodejs/

0 Response to "Node.js Express Upload Image to Database Example"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel