alan
/
sfu
1
Fork 0

initial version of simple file uploader

This commit is contained in:
Alan Faubert 2019-12-01 08:33:57 -05:00
parent 9e57320807
commit a31ab51301
1 changed files with 69 additions and 0 deletions

69
sfu.js Normal file
View File

@ -0,0 +1,69 @@
'use strict';
const Busboy = require('busboy');
const crypto = require('crypto');
const fs = require('fs');
const http = require('http');
const readline = require('readline');
if (process.argv.length < 3 || process.argv.length > 4) {
console.error('Arguments: <port> [host]');
process.exit(1);
}
const port = +process.argv[2];
const host = process.argv[3] || 'localhost';
const send_error = (res, code, message) => {
res.writeHead(code, { 'content-type': 'text/html; charset=utf-8' });
res.end(`<!doctype html>
<html>
<head>
<title>${code}: ${message}</title>
</head>
<body>
<h1>${code}: ${message}</h1>
</body>
</html>`);
};
http.createServer((req, res) => {
if (req.method === 'GET') {
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
res.end(`<!doctype html>
<html>
<head>
<title>Upload</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="file" multiple>
<input type="submit" value="Upload">
</form>
</html>`);
} else if (req.method === 'POST') {
const busboy = new Busboy({ headers: req.headers });
const dir = crypto.randomBytes(64).toString('hex');
fs.mkdirSync(dir);
busboy.on('file', (fieldname, file, filename) => {
if (filename.includes('/') || filename.includes('\\')) {
send_error(res, 403, 'Forbidden');
} else {
file.pipe(fs.createWriteStream(dir + '/' + filename));
}
});
busboy.on('finish', () => {
res.end(dir);
});
req.pipe(busboy);
} else {
send_error(res, 405, 'Method Not Allowed');
return;
}
}).listen(port, host);
console.log(`Serving on http://${host}:${port} - Press any key to stop`);
readline.emitKeypressEvents(process.stdin);
process.stdin.setRawMode(true);
process.stdin.on('keypress', () => process.exit(0));