Most Popular Tutorials
Most Popular Tutorials :-

Simply Easy Learning at Your Fingertips. Click Tutorials Menu to view More Tutorial List





How to upload files in node.js?

in node.js, for file upload you can use various module for file upload. these modules are :

  • Formidable
  • multer
  • you can download Formidable module and installed using NPM:

    File Name :

    C:\Users>mahtab_nodejs>npm install formidable

    ############################# OR ###############################

    C:\Users>mahtab_nodejs>npm install multer


    npm version multer

    npm install ejs
    npm install express
    npm install multer

    After download you can include the module in any application:

    var formidable = require('formidable');

    How to upload Files?

    File Name : file_upload.js

    var http = require('http');
    var formidable = require('formidable');
    var fs = require('fs');

    http.createServer(function (req, res) {
    if (req.url == '/fileupload') {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
    var oldpath = files.filetoupload.filepath;
    var newpath = 'C:/Users/Your Name/' + files.filetoupload.originalFilename;
    fs.rename(oldpath, newpath, function (err) {
    if (err) throw err;
    res.write('File uploaded and moved!');
    res.end();
    });
    });
    } else {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
    res.write('<input type="file" name="filetoupload"><br>');
    res.write('<input type="submit">');
    res.write('</form>');
    return res.end();
    }
    }).listen(8080);

    First Include the Formidable module to be able to parse the uploaded file once it reaches the server. When the file is uploaded and parsed, it gets placed on a temporary folder on your computer.

    When a file is successfully uploaded to the server, it is placed on a temporary folder. The path to this directory can be found in the "files" object, passed as the third argument in the parse() method's callback function.

    To move the file to the folder of your choice, use the File System module, and rename the file:


    signup

    File Name : signup.js

    <!DOCTYPE html>
    <html>

    <head>
    <title>FILE UPLOAD DEMO</title>
    </head>

    <body>
    <h1>Single File Upload Demo</h1>

    <form action="/uploadProfilePicture"
    enctype="multipart/form-data" method="POST">

    <span>Upload Profile Picture:</span>
    <input type="file" name="mypic" required/> <br>
    <input type="submit" value="submit">
    </form>
    </body>

    </html>

    index.js

    File Name : index.js

    const express = require("express")
    const path = require("path")
    const multer = require("multer")
    const app = express()

    // View Engine Setup
    app.set("views",path.join(__dirname,"views"))
    app.set("view engine","ejs")

    // var upload = multer({ dest: "Upload_folder_name" })
    // If you do not want to use diskStorage then uncomment it

    var storage = multer.diskStorage({
    destination: function (req, file, cb) {

    // Uploads is the Upload_folder_name
    cb(null, "uploads")
    },
    filename: function (req, file, cb) {
    cb(null, file.fieldname + "-" + Date.now()+".jpg")
    }
    })

    // Define the maximum size for uploading
    // picture i.e. 1 MB. it is optional
    const maxSize = 1 * 1000 * 1000;

    var upload = multer({
    storage: storage,
    limits: { fileSize: maxSize },
    fileFilter: function (req, file, cb){

    // Set the filetypes, it is optional
    var filetypes = /jpeg|jpg|png/;
    var mimetype = filetypes.test(file.mimetype);

    var extname = filetypes.test(path.extname(
    file.originalname).toLowerCase());

    if (mimetype && extname) {
    return cb(null, true);
    }

    cb("Error: File upload only supports the "
    + "following filetypes - " + filetypes);
    }

    // mypic is the name of file attribute
    }).single("mypic");

    app.get("/",function(req,res){
    res.render("Signup");
    })

    app.post("/uploadProfilePicture",function (req, res, next) {

    // Error MiddleWare for multer file upload, so if any
    // error occurs, the image would not be uploaded!
    upload(req,res,function(err) {

    if(err) {

    // ERROR occured (here it can be occured due
    // to uploading image of size greater than
    // 1MB or uploading different file type)
    res.send(err)
    }
    else {

    // SUCCESS, image successfully uploaded
    res.send("Success, Image uploaded!")
    }
    })
    })

    // Take any port number of your choice which
    // is not taken by any other process
    app.listen(8080,function(error) {
    if(error) throw error
    console.log("Server created Successfully on PORT 8080")
    })

    Run for output :-

    Run index.js file using below command:
    node index.js





    Previous Next


    Trending Tutorials




    Review & Rating

    0.0 / 5

    0 Review

    5
    (0)

    4
    (0)

    3
    (0)

    2
    (0)

    1
    (0)

    Write Review Here