daily pastebin goal
60%
SHARE
TWEET

file upload/save

a guest Feb 20th, 2019 81 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //npm install formidable
  2.  
  3. //upload file
  4. var http = require('http');
  5. var formidable = require('formidable');
  6.  
  7. http.createServer(function (req, res) {
  8.   if (req.url == '/fileupload') {
  9.     var form = new formidable.IncomingForm();
  10.     form.parse(req, function (err, fields, files) {
  11.       res.write('File uploaded');
  12.       res.end();
  13.     });
  14.   } else {
  15.     res.writeHead(200, {'Content-Type': 'text/html'});
  16.     res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
  17.     res.write('<input type="file" name="filetoupload"><br>');
  18.     res.write('<input type="submit">');
  19.     res.write('</form>');
  20.     return res.end();
  21.   }
  22. }).listen(8080);
  23.  
  24. // save file
  25.  
  26. var http = require('http');
  27. var formidable = require('formidable');
  28. var fs = require('fs');
  29.  
  30. http.createServer(function (req, res) {
  31.   if (req.url == '/fileupload') {
  32.     var form = new formidable.IncomingForm();
  33.     form.parse(req, function (err, fields, files) {
  34.       var oldpath = files.filetoupload.path;
  35.       var newpath = 'C:/Users/Your Name/' + files.filetoupload.name;
  36.       fs.rename(oldpath, newpath, function (err) {
  37.         if (err) throw err;
  38.         res.write('File uploaded and moved!');
  39.         res.end();
  40.       });
  41.  });
  42.   } else {
  43.     res.writeHead(200, {'Content-Type': 'text/html'});
  44.     res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
  45.     res.write('<input type="file" name="filetoupload"><br>');
  46.     res.write('<input type="submit">');
  47.     res.write('</form>');
  48.     return res.end();
  49.   }
  50. }).listen(8080);
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top