1

i'm trying to develop a simple file upload handler.

the only thing that i want is , this app receives a file from client and saves on hdd.

(i don't want to upload a file with nodejs , i just want to receive a file upload post and save it on my hdd)

how can i do this ?

i'm tried this way but , it does not works as expected.

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');
});

2
  • If your problem was solved by somebody's answer, please mark that answer as correct. If you came up with this answer yourself, please write it up as an answer in the answers section (not as part of the question) and mark it correct. Commented Jan 13, 2017 at 19:52
  • Additionally, we don't use [solved] title hacks here - use the acceptance system instead. You are welcome to accept your own answer, though if someone else helped you a great deal it is a nice gesture to accept theirs instead. Commented Jan 20, 2017 at 18:52

3 Answers 3

1

I've never used busboy before but the example given over in their GitHub documentation works fine.

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');
});

I've added some comments in the relevant section to make it more clear how it works. If you need more details, just comment below and I'll add them.

Sign up to request clarification or add additional context in comments.

8 Comments

Thanks Uzair :) Everything is fine but i can't save posted file with file.pipe(fs.createWriteStream('my.file')) method , what am i doing wrong ?
Make sure the path you're trying to write to is writeable by your node process. You can use ./my.file to make it relative, but safe way would be to use Current Working Directory and use path to join it. Example: path.join(process.cwd(), 'my.file'). This ensures the paths are correct on each OS. Second check would be to see if the console.log I added before the file.pip() line is being fired.
@developer.alp Also make sure you first test it with a small file, which is less than 500kb to make sure if the code is working. Larger files often cause problems which are unrelated to this piece of code.
thanks for your all ideas , I'm trying with 400kb , 300kb and a small text file , but 'console.log('Saving file at : ' + saveTo);' is not firing :( i'm testing this with postman , body is file , headers is Content-Type:multipart/form-data;boundary="test" , am i using postman with wrong method :( , i'm developing this uploading files (20-25 mb) , shall i use another library or app do you have any advices for me ? :)
I also tested this in Postman. To make sure Postman's configuration is correct, double check that your making the request as POST and that your URL is http://localhost:8000/ (used in my example). Also, Body should be set to form-data and make sure you are ONLY sending a single field and that field is of type File. Some upload libraries can't handle regular text fields with a file upload.
|
0

Simply use the FS api from node to write data received on file ? :)

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

3 Comments

good idea , I tried this on busboy.on('file') method but busboy.on('file') method not fired , any ideas :(
Are your sure you sending on multipart type ?
Yes it is.im testing it with rar and mp4 file.
0

Solved ,

i'm tried it with postman , i changed my mind and tried it with RESTClient , it works successfully now :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.