javascript - 在node.js中上传文件

标签 javascript node.js file-upload busboy

我在 Node.js 中上传文件时遇到问题。我不使用 express 。网上的大多数示例都是使用 Express 进行文件上传。 希望有任何指点。

function fileUploader2(req, res, next) {
var busboy = new Busboy({ headers: req.headers });
req.pipe(busboy);

busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
    console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype);
  //  var saveTo = path.join(os.tmpDir(), path.basename(fieldname));
    file.pipe(fs.createWriteStream('./upload/' + filename));
});
busboy.on('finish', function() {
    res.writeHead(200, { 'Connection': 'close' });
    res.end("That's all folks!");
});


res.end();

};

上面的方法不起作用。再说一遍,我没有使用 express 。将不胜感激任何帮助。

最佳答案

在这里,我给你做了一个例子。它对我有用。

const Busboy = require('busboy');
const http = require('http');
const fs = require('fs');

const server = http.createServer((req, res) => {
  var busboy = new Busboy({
    headers: req.headers
  });
  busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
    saveTo = `${__dirname}/${filename}`;
    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();
});

server.listen(8000, function() {
  console.log('magic at 8000');
});

关于javascript - 在node.js中上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37649583/

相关文章:

scala - 在playframework 2/scala中上传多个大文件和其他表单数据

php - 在自己的插件中为 Wordpress Media Uploader 自定义上传目录

swift - Firebase连续上传中途停止,只上传最后一张图片

"unexpected token"上的 Node.js 语法错误 "exports."

Javascript 相当于 WHERE 子句中带有 NULL 的 LEFT OUTER JOIN

javascript - lodash绑定(bind)函数用作jQuery事件处理程序...可能吗?

javascript:将 classList 替换为条件条件

javascript - HTML - CSS - 响应式相同尺寸的图像网格,悬停时出现框

javascript - socket.send() 不适用于 Opera 11.10

javascript - 从 Graph 获取单个消息