Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the size of a file, with uploading and POST request

Please note: I want to do this with vanilla Node.

I want to upload a file with the input type="file" HTML tag, and in the same form element hit a submit button input type="submit" and get the size of the file in bytes when I submit a POST request.

Thanks

like image 977
JohnSnow Avatar asked Sep 21 '25 05:09

JohnSnow


1 Answers

Something like the following should work:

var http = require('http');

var server = http.createServer(function(req, res) {
  switch (req.url) {
    case '/':
      display_form(req, res);
      break;
    case '/upload':
      show_bytes(req, res);
      break;
    default:
      res.writeHead(404, {'content-Type': 'text/plain'});
      res.write('not found');
      res.end();
      break;
  }
});
server.listen(3000);

function display_form(req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write(
    '<form action="/upload" method="post" enctype="multipart/form-data">'+
    '<input type="file" name="upload">'+
    '<input type="submit" value="Submit">'+
    '</form>'
  );
  res.end();
}

function show_bytes(req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.write(req.headers['content-length'] +  ' bytes');
  res.end();
}
like image 57
dNitro Avatar answered Sep 22 '25 22:09

dNitro