72 lines
1.8 KiB
JavaScript
Executable File
72 lines
1.8 KiB
JavaScript
Executable File
#!/usr/bin/env node
|
|
|
|
'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));
|