Permalink
Browse files

nodejs-server multipart

  • Loading branch information...
1 parent b84f5cb commit f61b0c1e61ca5d64a579f428a4278a4ce1862499 @guybrush committed Jan 8, 2011
Showing with 30 additions and 11 deletions.
  1. +11 −8 server/nodejs/README.md
  2. +19 −3 server/nodejs/server.js
View
@@ -1,14 +1,13 @@
# file-uploader with node.js
This is an example of using file-uploader with [node.js](http://nodejs.org).
+It uses [connect](https://github.com/senchalabs/connect) for the sake of
+simplicity. Multipart messages will be parsed with
+[formidable](https://github.com/felixge/node-formidable) and the octet-stream
+will be written to disk directly (via the new awesome Stream-API of
+nodejs-v0.3.3).
-*Note:* One could just use [formidable](https://github.com/felixge/node-formidable)
-to upload files and send the upload-% from server to client (websockets,
-longpoll, what ever). Which might be the better option. This is just for those,
-who want a ready-to-use client-side implementation of an feature-rich
-upload-button, which comes with file-uploader.
-
-Installing node.js:
+Installing node.js (v0.3.3+):
curl http://nodejs.org/dist/node-v0.3.3.tar.gz
tar xzvf node-v0.3.3.tar.gz
@@ -19,7 +18,11 @@ Install modules (with npm):
curl http://npmjs.org/install.sh | sh
npm install connect
+ npm install formidable
Now the server can be started with `node server.js`. The server will listen on
port 3000 and saves the uploaded files in `../uploads`. Browse
-`http://localhost:3000` and enjoy file-uploader with node.js!
+`http://localhost:3000` and enjoy file-uploader with node.js!
+
+Any suggestions/questions/critique/.. is very welcome -
+[guybrush](https://github.com/guybrush)
View
@@ -4,18 +4,34 @@
var connect = require('connect')
, fs = require('fs')
+ , formidable = require('formidable')
, uploadDir = __dirname+'/../uploads/'
, port = 3000
- , body, fileStream, server, socket, uploader
+ , files = []
+ , fields = []
+ , body, fileStream, server, socket, uploader, form
uploader = function(req, res, next) {
- if (req.headers['content-type'].match(/application\/octet-stream/i)) {
+ if (req.headers['content-type'].match(/multipart\/form-data/i)) {
+ form = new formidable.IncomingForm()
+ form.keepExtensions = true
+ form.uploadDir = uploadDir
+ form.parse(req, function(err, fields, files){
+ body = '{"success":"true"}'
+ res.writeHead(200,
+ { 'Content-Type':'text/html'
+ , 'Content-Length':body.length
+ })
+ res.end(body)
+ })
+ }
+ else if (req.headers['content-type'].match(/application\/octet-stream/i)) {
fileStream = fs.createWriteStream(uploadDir+req.headers['x-file-name'])
req.pipe(fileStream)
req.on('end', function() {
body = '{"success":"true"}'
res.writeHead(200,
- { 'Content-Type':'text/plain'
+ { 'Content-Type':'text/html'
, 'Content-Length':body.length
})
res.end(body)

0 comments on commit f61b0c1

Please sign in to comment.