Node(20) File Upload with formidable module

来源:互联网 发布:java sleep1000 编辑:程序博客网 时间:2024/04/20 00:37

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 filesif( request.method === 'POST' ){//create a formidable incomingFormvar incoming = new formidable.IncomingForm();//upload to uploads folderincoming.uploadDir = 'uploads';//listen to file eventincoming.on('fileBegin', function(field,file){//appended the origin filename at the end after random filenameif( 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




原创粉丝点击