It’s been quite a while I didn’t post anything in this blog, I was kept busy everyday even though I don’t know why.

Few days ago I’m required to implement a simple file upload interface, in order test the API I developed a mock node.js server which will take the uploaded file. The mock is built with express.js.

Don’t forget to install two package:

1
2
npm install --save formidable
npm install --save fs-extra

Now the project source tree is like this:

Here’s the code, ##index.js##

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
var express = require('express');
var router = express.Router();
var formidable = require('formidable');
var fs =require('fs-extra'); //File System-needed for renaming file etc

/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});

router.post('/upload', function(req, res, next0) {
var form = new formidable.IncomingForm();
//Formidable uploads to operating systems tmp dir by default
form.uploadDir = "img"; //set upload directory
form.keepExtensions = true; //keep file extension

form.parse(req, function(err, fields, files) {
res.writeHead(200, {'content-type': 'text/plain'});
res.write('received upload:\n\n');
console.log("form.bytesReceived");
//TESTING
console.log("file size: "+JSON.stringify(files.fileUploaded.size));
console.log("file path: "+JSON.stringify(files.fileUploaded.path));
console.log("file name: "+JSON.stringify(files.fileUploaded.name));
console.log("file type: "+JSON.stringify(files.fileUploaded.type));
console.log("astModifiedDate: "+JSON.stringify(files.fileUploaded.lastModifiedDate));

//Formidable changes the name of the uploaded file
//Rename the file to its original name
fs.rename(files.fileUploaded.path, './img/'+files.fileUploaded.name, function(err) {
if (err)
throw err;
console.log('renamed complete');
});
res.end();
});
});

module.exports = router;

And we need a page ##index.jade## to test the server:

1
2
3
form(method="post", action="upload", enctype="multipart/form-data")
input(type="file", name="fileUploaded")
input(type="submit")