Upload Video Using Formidable in Nodejs

Before doing anything, we have to know about formidable.

This module is focused on uploading and encoding images and videos. It has been battle-tested against hundreds of GBs of file uploads from a large variety of clients and is considered production-ready and is used in production for years.

In this blog, we are discussing how to upload a video file in nodejs. Let’s start with a blank project. Open a folder directory and create a project “videoupload”.

You can check my previews blog, I discussed the basic crud app in nodejs. we can go check the blog. Now we can create two files db.js and app.js.

After that, we can install some npm package like body-parser, path, formidable, sequelize, etc. If you don’t know about the packages you can go to your browser and check the packages.

Using formidable we can upload any file, that file may have an image or video or any text files. So, This is a low-level package, and if you're using a high-level framework it may already be included. However, Express v4 does not include any multipart handling, nor does body-parser.

In this project, we also install sequelize npm that also is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite, and Microsoft SQL Server. It features solid transaction support, relations, eager and lazy loading, read replication, and more.

So, let’s start with the model:
module.exports = function(sequelize, DataTypes) {
    return sequelize.define(videos', {
      id: {
        type: DataTypes.INTEGER(11),
        allowNull: false,
        primaryKey: true,
        autoIncrement: true
      },
      name: {
        type: DataTypes.STRING(255),
        allowNull: false
      },  
      intro_video: {
        type: DataTypes.STRING(255),
        allowNull: false
      },      
      createdBy: {
        type: DataTypes.STRING(100),
        allowNull: true
      },
      updatedBy: {
        type: DataTypes.STRING(100),
        allowNull: true
      },
      createdAt: {
        type: DataTypes.DATE,
        allowNull: true
      },
      updatedAt: {
        type: DataTypes.DATE,
        allowNull: true
      }    
    }, {
      tableName: 'videos'
    });
  };


For the add and edit page:  For the view page we using ejs.



required="required"<% }%> onclick="return(confirm('Plase Upload .mp4 only'));" >   <% if(arrData && arrData !=''){ %> <% } %>
     
Controller page:
exports.add = function(req, res, next) {

    var d = new Date();
//Need to create another valiable
    var n = d.getTime();
    var form = new multiparty.Form();
    form.parse(req, function(err, fields, files) { 
        var id = fields.update_id[0];

        if(files.intro_video[0].originalFilename!=''){                   
            
            var intro_video=req.app.locals.baseurl+'/set your directory where you want upload the video '+n+files.intro_video[0].originalFilename;
        }else{
            var intro_video= fields.update_intro_video ? fields.update_intro_video[0]: '';
        }

        if(!id){
          
            models.nodetest.create({ 

    name: fields.name ? fields.name[0]:null, 
                intro_video: intro_video
               
                }).then(function(user) {  
                     
                    req.flash('info','Successfully Created');
                    return res.redirect('back');
                })
                .catch(function(error) {
                    return res.send(error);
                });
        }
        else{
            models.nodetest.update({ 
                name: fields.name ? fields.name[0]:null, 
                intro_video: intro_video
                
            },{where:{id:id}}).then(function(user) {
                req.flash('info','Successfully Updated');
                return res.redirect('back');
            })
            .catch(function(error) {
                return res.send(error);
            });
        }
    });
    var formnew = new formidable.IncomingForm();
    formnew.parse(req);    

// in formidable we can increases the file size
    form.maxFileSize = 10 * 1024 * 1024 * 1024;

    formnew.on('fileBegin', function(field, file) {        
    console.log("video  is Here");
    console.log(file);  
    //return res.send(file);
    //Checking File type    
        if(file.name!=''){
            if(file.type=='video/mp4' ){
                console.log(__dirname);
                file.path = __dirname + '/set your directory where you want upload the video /'+n+ file.name;
             
            }else{
            //  req.flash('errors','Please upload a supported file.');
                return res.redirect('back');
            }   
        }
    });
}

Conclusion:

It is very important for Ionic mobile app development. So, please read the blog and share your review on the comment section.

We Serve clients globally in diverse industries

Stay Upto Date With Our Newsletter.