Tuesday, August 26, 2014

web server make with post, get request and multipart/form-data using Node.js

http_server.js


//npm install -g formidable
var formidable = require('formidable'),
sys = require('sys'),
http = require('http'),
util = require('util'),
url = require('url'),
qs = require('querystring');

http.createServer(function(request, response){
    if (request.url == '/upload' && request.method.toLowerCase() == 'post') {
        var body = '';
        request.on('data', function(data){
            body += data;
        });
        request.on('end', function(){
            //var jobj =  json.parse(body);
            //console.log(jobj.title);
            //var post =  qs.parse(body);           
        });
       
        // Instantiate a new formidable form for processing.
        var form = new formidable.IncomingForm();
       
        // form.parse analyzes the incoming stream data, picking apart the different fields and files for you.
        form.parse(request, function(err, fields, files) {
            if (err) {
                // Check for and handle any errors here.
                console.error(err.message);
                return;
            }
            response.writeHead(200, {'content-type': 'text/plain'});
            response.write('Received Upload:\n\n');
           
            // This last line responds to the form submission with a list of the parsed data and files.
            response.end(util.inspect({fields: fields, files: files}));
        });
        return;
    }
    else if(request.method == 'GET') {
        var url_parts = url.parse(request.url, true);
        console.log(url_parts.query);
    }
   
    // If this is a regular request, and not a form submission, then send the form.
    response.writeHead(200, {'content-type': 'text/html'});
    response.end(
        '<form action="/upload" enctype="multipart/form-data" method="post">'+
        '<label>title:</label><input type="text" name="title"><br>'+
        '<label>file:</label><input type="file" name="files" multiple="multiple"><br>'+
        '<input type="submit" value="Upload">'+
        '</form>'
    );
}).listen(8080);
//server is response.write();


result


No comments: