Skip to content Skip to sidebar Skip to footer

Node.js Upload Files To Server Without Additionals Frameworks

I'm writing a simple uploading website. I use XmlHTTPRequest to upload files. Until now I've experienced only this part, with server already prepared for file uploading. But now I

Solution 1:

Ok, eventually I've solved it this way, with use of fs and formidable. The communication between web app and server is a classical request-response, it's very easy to handle in Node.js.

Here is the full server code: http://pastebin.com/cmZgSmrL


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

    //-----------------------//-------------------------------------------------------------------------------------//--- UPLOAD handling ---////-----------------------//if (req.url == '/upload' && req.method.toLowerCase() == 'post') {
            var form = new formidable.IncomingForm();

            form.parse(req, function(err, fields, files) {
                    if (err) throw err;

                    fs.readFile( files.filepath.path, function (err, data) {
                            if (err) throw err;

                            var fileName = files.filepath.name;
                            fs.writeFile( __dirname + '/uploadedFiles/' + fileName, data, function (err) {
                                    if (err) throw err;

                                    //-----------------------------------------------//---------------------------------------------//--- LOAD and APPEND external JSON file with ---////--- data from request                       ---////-----------------------------------------------//var jsonObj = require('./storedFilesList.json');

                                    jsonObj[fileName] = {size:files.filepath.size, expDate:'-', path:__dirname + '/uploadedFiles/' + fileName};

                                    var jsonString = JSON.stringify(jsonObj); // convert JSON obj to String

                                    fs.writeFile('storedFilesList.json', jsonString, function(err){
                                            if (err) throw err;
                                            console.log('File ' + fileName + ' was succesfully written to JSON ext file.');
                                    });

                                    console.log('File ' + fileName + ' was succesfully saved.');
                            });
                    });

                    res.writeHead(200, {'content-type': 'text/plain'});
                    res.write('OK');
                    res.end( util.inspect({fields: fields, files: files}) );
            });

            return;
    }

Post a Comment for "Node.js Upload Files To Server Without Additionals Frameworks"