NodeJS - 服务器端文件上传处理程序

时间:2017-01-12 20:05:00

标签: node.js

我正在尝试开发一个简单的文件上传处理程序。

我唯一需要的是,这个应用程序从客户端接收文件并保存在硬盘上。

(我不想上传带有nodejs的文件,我只想收到一个文件上传帖子并将其保存在我的硬盘上)

我该怎么做?

我试过这种方式但是,它没有按预期工作。



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

var Busboy = require('busboy');

http.createServer(function(req, res) {
  if (req.method === 'POST') {
		
	try{

    var busboy = new Busboy({ headers: req.headers });
    busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
		
		 var fstream = fs.createWriteStream('asdasd'); 
        file.pipe(fstream);
        fstream.on('close', function () {
			res.writeHead(200, { 'Connection': 'close' });
            res.send('upload succeeded!');
        });
		
      /*var saveTo = path.join(os.tmpDir(), path.basename(fieldname));
      file.pipe(fs.createWriteStream('./output.asdasd'));
	  fstream.*/
    });
    busboy.on('finish', function() {
      res.writeHead(200, { 'Connection': 'close' });
      res.end("That's all folks!");
    });
    return req.pipe(busboy);
	}
	catch(err){
		console.log('error : ' + err);
		res.writeHead(404);
		res.end();
	}
  }
  res.writeHead(404);
  res.end();
}).listen(4842, function() {
  console.log('Listening for requests');
});




3 个答案:

答案 0 :(得分:1)

我之前从未使用过busboy,但在GitHub documentation中提供的示例效果很好。

let http = require('http'),
  path = require('path'),
  os = require('os'),
  fs = require('fs');

let Busboy = require('busboy');

http.createServer(function (req, res) {

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

    let busboy = new Busboy({ headers: req.headers });

    // handle all incoming `file` events, which are thrown when a FILE field is encountered
    // in multipart request
    busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {

      // figure out where you want to save the file on disk
      // this can be any path really
      let saveTo = path.join(os.tmpdir(), path.basename(filename));

      // output where the file is being saved to make sure it's being uploaded
      console.log(`Saving file at ${saveTo}`);

      // write the actual file to disk
      file.pipe(fs.createWriteStream(saveTo));
    });

    busboy.on('finish', function () {

      res.writeHead(200, { 'Connection': 'close' });
      res.end("That's all folks!");
    });

    return req.pipe(busboy);
  }

  res.writeHead(404);
  res.end();

}).listen(8000, function () {
  console.log('Listening for requests');
});

我在相关部分添加了一些评论,以便更清楚地了解其工作原理。如果您需要更多详细信息,请在下面进行评论,我会添加它们。

答案 1 :(得分:0)

只需使用节点的FS api写入文件中收到的数据? :)

https://nodejs.org/api/fs.html#fs_class_fs_writestream

答案 2 :(得分:0)

解决,

我和postman一起尝试过,我改变了主意,用RESTClient尝试了它,现在它成功了:)