Skip to content

Instantly share code, notes, and snippets.

@chulman444
Last active September 20, 2018 00:39
Show Gist options
  • Save chulman444/9a5a9607a30c41a5bc72c16aa6e001b2 to your computer and use it in GitHub Desktop.
Save chulman444/9a5a9607a30c41a5bc72c16aa6e001b2 to your computer and use it in GitHub Desktop.
Upload to node server file
<!-- public/index.html -->
<form action="fileupload" method="post" enctype="multipart/form-data">
<input type="file" name="filetoupload"><br>
<input type="submit">
</form>
const express = require("express");
const app = express();
const formidable = require('formidable');
const fs = require('fs');
const path = require("path")
app.use(express.static("public"));
app.post("/fileupload", (req, res) => {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
var oldpath = files.filetoupload.path;
var newpath = path.join(__dirname, files.filetoupload.name)
// Read the file
fs.readFile(oldpath, function (err, data) {
if (err) throw err;
console.log('File read!');
// Write the file
fs.writeFile(newpath, data, function (err) {
if (err) throw err;
res.write('File uploaded and moved!');
res.end();
console.log('File written!');
});
// Delete the file
fs.unlink(oldpath, function (err) {
if (err) throw err;
console.log('File deleted!');
});
});
});
});
app.listen(8080, ()=> {
console.log("WORKING 8080");
});
var http = require('http');
var formidable = require('formidable');
var fs = require('fs');
const path = require("path")
http.createServer(function (req, res) {
if (req.url == '/fileupload') {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
var oldpath = files.filetoupload.path;
var newpath = path.join(__dirname, files.filetoupload.name)
// Read the file
fs.readFile(oldpath, function (err, data) {
if (err) throw err;
console.log('File read!');
// Write the file
fs.writeFile(newpath, data, function (err) {
if (err) throw err;
res.write('File uploaded and moved!');
res.end();
console.log('File written!');
});
// Delete the file
fs.unlink(oldpath, function (err) {
if (err) throw err;
console.log('File deleted!');
});
});
});
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
res.write('<input type="file" name="filetoupload"><br>');
res.write('<input type="submit">');
res.write('</form>');
return res.end();
}
}).listen(8080);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment