繁体   English   中英

不使用express.js将图像保存到Node.js服务器

[英]Saving image to node.js server without express.js

所以我一直想知道如何在不使用express的情况下将图像保存到node.js服务器(只是学习节点,并希望让我自己做的一切都能更好地学习节点,而无需express)。

到目前为止,我有一个带有图像的表格,仅作为输入,是随我的要求发送的。 这是我到目前为止在服务器上所没有的内容。

if(req.method === 'POST') {

    if (req.url === '/upload') {

        req.on('error', function(e) {
          console.log('Problem with request: ' + e.message);
        });

        res.writeHead(200, {'Content-Type': 'image/jpg; charset=utf8'});

        req.on('data', function (chunk) {

            fs.writeFile(__dirname + "/uploads/dada.jpg", chunk, function(err) {
                if(err) {
                    console.log(err);
                } else {
                    console.log("The file was saved!");
                }
            }); 
        });
    }
}

这是我的表格:

<form method="post" action="/upload" enctype="multipart/form-data">

编辑:我解决了大多数问题,但文件仅保存为图像,但无法像一个文件一样查看。 (我猜内容类型有问题,但不知道如何解决) 是我整个应用程序的不足。 我知道我需要将其分离到不同的模块中,但是我稍后会做

我完全忘记了这个老问题,但是现在我看到它有很多看法,这是我找到的解决方案:

var port = 1357;

var http = require('http'),
    path = require('path'),
    mime = require('mime'),
    fs = require('fs'),
    GUID = require('GUID'),
    formidable = require('formidable'),
    util = require('util');

var app = http.createServer(function (req, res) {

    if (req.method === 'POST') {

        if (req.url === '/upload') {

            req.on('error', function (e) {
                console.log('Problem with request: ' + e.message);
            });

            var fileDirectory = __dirname + '/db/',
                form = new formidable.IncomingForm();

            form.keepExtensions = true;
            form.uploadDir =fileDirectory;

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

                if (err) throw (err);

                var pic = JSON.stringify(util.inspect(files)),
                    upIndx = pic.indexOf('db'),
                    path = pic.slice(upIndx + 6, upIndx + 42);

                res.writeHead(200, {
                    'Content-Type': 'text/html'
                });
                fs.readFile('views/index.html', function (err, page) {
                    res.writeHead(200, {
                        'Content-Type': 'text/html'
                    });
                    res.write(page);
                    res.write('<div>Download Link: </div><div>' + fileDirectory + path + '</div>');
                    res.end();
                });
            });

        }
    } else {

        //not important for question, handle other request
    }

});

app.listen(port);
console.log('Server running on port: ' + port)

暂无
暂无

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

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