• Download Gist
multipart-js file stream upload example by me.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
var sys = require("sys"),
fs = require('fs'),
url = require('url'),
http = require("http"),
multipart = require("./lib/multipart");
 
var name, filename, file,file2;
 
http.createServer(function (request, response) {
switch (url.parse(request.url).pathname) {
case '/':
display_form(request, response);
break;
case '/upload':
upload_file(request, response);
break;
default:
show_404(request, response);
break;
}
}).listen(8124);
 
function display_form(request, response) {
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(
'<form action="/upload" method="POST" enctype="multipart/form-data">' +
'<input type="file" name="upload-file">' +
'<input type="submit" value="Upload">' +
'</form>'
);
response.end();
}
 
function upload_file(request, response) {
request.setEncoding('binary');
 
file2 = fs.createWriteStream("./parse_log");
//file2.setEncoding('binary');
// parsing
var parser = multipart.parser();
parser.headers = request.headers;
/*sys.pump(request.connection, parser, function()
{
sys.debug('request end');
parser.close();
});*/
request.addListener('end', function()
{
sys.debug('request end');
parser.close();
});
parser.addListener('onPartBegin', function(part) {
// sys.debug(sys.inspect(part));
name = part.name;
filename = part.filename;
file = fs.createWriteStream("./" + filename);
//fs.open(path, flags, mode=0666, [callback])
//file.setEncoding('binary');
});
parser.addListener('onPartEnd', function(part) {
file.end();
file2.end();
sys.debug(' parser on part end ');
});
parser.addListener('onData', function(chunk) {
file.write(chunk,'binary');
// function(err, bytesWritten) {
// sys.debug('bytes written: ' + bytesWritten);
// }
});
 
 
parser.addListener('onEnd', function(part)
{
sys.debug(' parser on end ');
response.writeHead(200, {'Content-Type': 'text/plain'});
response.write('Thanks for the upload');
response.end();
});
parser.addListener('onError', function(part)
{
sys.debug(' parser on end ');
response.writeHead(200, {'Content-Type': 'text/plain'});
response.write('Error for the upload');
response.end();
});
 
request.addListener('data', function(chunk)
{
sys.debug('request data');
file2.write(chunk,'binary');
parser.write(chunk) ;
});
}
 
function show_404(request, response) {
response.writeHead(404, {'Content-Type': 'text/plain'});
response.write('404 - Please try again.');
response.end();
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.