将图像保存到没有express.js的node.js服务器

所以我一直想知道如何将图像保存到node.js服务器,而不使用express。(只是学习节点,并希望使自己的一切,以更好地学习节点,没有expression)。

到目前为止,我有一个forms与图像作为唯一的input,我发送一个职位请求。 这是我迄今为止在我的服务器上,它不logging任何东西。

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!"); } }); }); } } 

这是我的forms:

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

编辑:我解决了大部分问题,但文件只保存为图像,但不能像一个。 (我猜的内容types有问题,但不知道如何解决) 这是我的整个应用程序的小提琴。 我知道我需要把它分成不同的模块,但我会在稍后做

我完全忘了这个老问题,但现在我看到它有一些意见,这里是我find的解决scheme:

 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)