简体   繁体   中英

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 need to make my own server to test this web app locally. I've chosen Node.js, because it uses JavaScript and appears quite simple in comparison to other servers. But still, I'm not very experienced in using this, so I don't know, how to "catch" uploaded files from request and save them to some folder located in my PC. I've been trying to find a solution, but every one I've found is using some framework. I don't want to use these, if possible, because I don't want to add any complexity to my server code, since it's not the main point of my project and I need it really the simplest possible, just for testing purposes.

So, could you please recommend me some easy way to do this? If you think, that "clear" Node.js without frameworks is not ideal, feel free to describe any other solution, I'll try my best to understand it :-)


I've written the basic part of the server which print some statements and loads my source codes:

var http = require('http');
var fs = require('fs');
var path = require('path');

http.createServer(function(request, response) {
    console.log(request.method + ' ' + request.url);
    var filePath = '.' + request.url;
    if (filePath == './')
        filePath = './index.html';
    if (filePath.indexOf('/../') !== -1) {
        response.writeHead(400);
        response.end();
    } else {
        var extname = path.extname(filePath);
        var contentType = 'text/plain';
        switch (extname) {
            case '.js': contentType = 'text/javascript'; break;
            case '.html': contentType = 'text/html'; break;
            case '.css': contentType = 'text/css'; break;
        }
        fs.exists(filePath, function(exists) {
            if (exists) {
                fs.readFile(filePath, function(error, content) {
                    if (error) {
                        response.writeHead(500);
                        response.end();
                    } else {
                        response.writeHead(200, { 'Content-Type': contentType });
                        response.end(content, 'utf-8');
                    }
                });
            } else {
                response.writeHead(404);
                response.end();
            }
        });
    }
}).listen(8080);

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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM