簡體   English   中英

Node.js無需附加框架即可將文件上傳到服務器

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

我正在寫一個簡單的上傳網站。 我使用XmlHTTPRequest上傳文件。 到目前為止,我只經歷了這一部分,服務器已經為文件上傳做好了准備。 但是,現在我需要制作自己的服務器才能在本地測試此Web應用程序。 我選擇了Node.js,因為它使用JavaScript,並且與其他服務器相比看起來非常簡單。 但是,我在使用此文件方面還不是很有經驗,所以我不知道如何從請求中“捕獲”上傳的文件並將其保存到PC上的某個文件夾中。 我一直在嘗試找到一種解決方案,但是我發現的每個解決方案都在使用某種框架。 如果可能的話,我不想使用它們,因為我不想在服務器代碼中增加任何復雜性,因為它不是我項目的重點,並且我真的需要最簡單的方法來進行測試。

因此,您能推薦我一些簡單的方法來做到這一點嗎? 如果您認為沒有框架的“清晰” Node.js是不理想的,請隨意描述任何其他解決方案,我將盡力理解它:-)


我已經寫了服務器的基本部分,可以打印一些語句並加載我的源代碼:

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

好的,最終我已經通過使用fs可怕的方法解決了這個問題。 Web應用程序與服務器之間的通信是經典的請求響應,在Node.js中很容易處理。

這是完整的服務器代碼: 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