1

I am having a problem in uploading a file in node.js. Am not using express. and most of the examples online are file upload using expres.. WOuld appreciate any pointers.

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

};

The above does not work . Again I am not using express. Would appreciate any help.

Jitin
  • 41
  • 4
  • You need to be more specific about what doesn't work. Where are *req, res, next* coming from if you are not using express? – Molda Jun 06 '16 at 05:30

1 Answers1

0

Here, I've made an example for you. It worked for me.

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');
});
Relu Mesaros
  • 4,952
  • 4
  • 25
  • 33