File Upload in Nodejs

We can upload one or many files in a folder using Nodejs and We also can save its name into a Database. File Upload in Nodejs.

I am using Node framework EXPRESS and multer for file upload into a folder. You can install the express framework by using the below command

npm install express

Install multer using the below command

npm install –save multer file upload node

Now make a file in the Node folder with the named service.js

service.js

var express =   require("express");
var multer  =   require('multer');
var app         =   express();
var storage =   multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, './uploads');
  },
  filename: function (req, file, callback) {
    callback(null, file.fieldname + '-' + Date.now());
  }
});
var upload = multer({ storage : storage}).single('userPhoto');

app.get('/',function(req,res){
      res.sendFile(__dirname + "/index.html");
});

app.post('/api/photo',function(req,res){
    upload(req,res,function(err) {
        if(err) {
            return res.end("Error uploading file.");
        }
        res.end("File is uploaded");
    });
});

app.listen(3000,function(){
    console.log("Working on port 3000");
});

Now I will use an HTML Form for File uploading,

<form id        =  "uploadForm"
     enctype   =  "multipart/form-data"
     action    =  "/api/photo"
     method    =  "post"
>
<input type="file" name="userPhoto" />
<input type="submit" value="Upload Image" name="submit">
</form>

Now Run the project using this command node service.js

This project will run on 3000 Port because I set 3000

See our More Project

Nodejs Connection in MongoDB

Routing in Node.js

Live Search with React and NodeJS

CRUD Operation Using React & Nodejs

Leave a Reply

Your email address will not be published. Required fields are marked *