Node(20) File Upload with formidable module

handling file upload needs to include formidable module, writing raw code for file upload is tough.


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

var form = require('fs').readFileSync('form.html');

http.createServer( function(request, response){
	
	//handle post files
	if( request.method === 'POST' ){
		//create a formidable incomingForm
		var incoming = new formidable.IncomingForm();
		
		//upload to uploads folder
		incoming.uploadDir = 'uploads';
		
		//listen to file event
		incoming.on('fileBegin', function(field,file){
			//appended the origin filename at the end after random filename
			if( file.name ){
				file.path += "_" + file.name
			}
		}).on( 'file', function( field, file ){
			if( !file.size){
				return;
			}
			response.write( file.name + ' received\n');
		}).on( 'end', function(){
			response.end( 'All files received');
		}).on( 'field', function( field, value ){
			response.write( field + ' - ' + value + '\n');
		});
		incoming.parse(request );
	}
	
	//handle get
    if (request.method === "GET") {
        response.writeHead(200, {
            'Content-Type': 'text/html'
        });
        response.end(form);
    }
	
}).listen(9000);



note: formidable can also handle POST data using 'field' event


Reference




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章