Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • File Upload in Node.js

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.32k
    Comment on it

    Form processing and file handling are very common and important part of any web application. Now with express, handling file uploads becomes very easy. So far we have seen and used req.body now we have req.files. req.files contains all the information about the file, that is being uploaded by us.
    Lets create an application to upload a file. In this blog i have used connect-multiparty middleware for multipart.

    let's create a form:

    <form method="post" enctype="multipart/form-data" action="/uploadFile">
        <input type="file" name="thumbnail">
        <input type="submit">
    </form>

    To handle multipart we wll install connect-multiparty using npm:

    npm install connect-multiparty

    Now we include connect-multiparty in our application, so open app.js and add the below code:

    var multipart = require('connect-multiparty');
    var multipartMiddleware = multipart();
    var fs = require('fs');
    app.post('/uploadFile', multipartMiddleware, function(req, resp) {
        var tmp_path = req.files.thumbnail.path;
        var target_path = './public/images/' + req.files.thumbnail.name;
        fs.rename(tmp_path, target_path, function(err) {
            if (err) throw err;
            fs.unlink(tmp_path, function() {
                if (err) throw err;
                res.send('File uploaded to: ' + target_path);
            });
        });
     
    });

    We have to be careful while using connect-multiparty middleware as it creates temp files on server and never clean them up.Thus we should add this middleware to only one route that accept uploads.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: