简体   繁体   English

Node.js无需附加框架即可将文件上传到服务器

[英]Node.js upload files to server without additionals frameworks

I'm writing a simple uploading website. 我正在写一个简单的上传网站。 I use XmlHTTPRequest to upload files. 我使用XmlHTTPRequest上传文件。 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. 但是,现在我需要制作自己的服务器才能在本地测试此Web应用程序。 I've chosen Node.js, because it uses JavaScript and appears quite simple in comparison to other servers. 我选择了Node.js,因为它使用JavaScript,并且与其他服务器相比看起来非常简单。 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. 但是,我在使用此文件方面还不是很有经验,所以我不知道如何从请求中“捕获”上传的文件并将其保存到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 :-) 如果您认为没有框架的“清晰” Node.js是不理想的,请随意描述任何其他解决方案,我将尽力理解它:-)


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 . 好的,最终我已经通过使用fs可怕的方法解决了这个问题。 The communication between web app and server is a classical request-response, it's very easy to handle in Node.js. Web应用程序与服务器之间的通信是经典的请求响应,在Node.js中很容易处理。

Here is the full server code: http://pastebin.com/cmZgSmrL 这是完整的服务器代码: 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;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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