Skip to content

Instantly share code, notes, and snippets.

@jsdevel
Last active January 4, 2018 06:11
Show Gist options
  • Save jsdevel/c37284713f13f41e6145ed16bf826b72 to your computer and use it in GitHub Desktop.
Save jsdevel/c37284713f13f41e6145ed16bf826b72 to your computer and use it in GitHub Desktop.
Shows how to handle file uploads in node.js line by line.
const http = require('http');
const readline = require('readline');
const HTML_PAGE = `<!doctype html>
<html>
<head>
<title>File upload testing</title>
<meta charset="utf-8">
<script>
function handleSubmit(e) {
e.preventDefault();
const file = document.querySelector('[type=file]').files[0];
if (!file) {
alert('You must select a file!');
} else {
const xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:3000', true);
xhr.send(file);
}
}
</script>
</head>
<body>
<h1>Try uploading a file</h1>
<form onsubmit="handleSubmit(event)">
<input type="file">
<br>
<button type="submit">submit</button>
</form>
</body>
</html>`;
http.createServer((req, res) => {
if (req.method === 'POST') {
const rl = readline.createInterface({
input: req
});
let lineNumber = 0;
rl.on('line', line => {
++lineNumber;
if (line.indexOf('http://') === -1) {
rl.close();
res.statusCode = 500;
return res.end(`line ${lineNumber} was invalid`);
}
console.log(`line ${lineNumber}: ${line}`);
});
rl.on('error', err => {
console.log('err', err);
});
req.on('end', () => {
console.log('done');
res.end('All done!');
});
} else if (req.method === 'GET') {
res.end(HTML_PAGE);
} else {
res.statusCode = 500;
res.end('Unknown method');
}
}).listen(3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment