hw4: ex4 passes tests
This commit is contained in:
parent
ceccf9ff43
commit
50d194ac2d
1 changed files with 50 additions and 3 deletions
|
@ -4,6 +4,7 @@
|
|||
const http = require('http');
|
||||
const url = require('url');
|
||||
const fs = require('fs');
|
||||
const formidable = require('formidable');
|
||||
|
||||
const routes = Object.create(null);
|
||||
|
||||
|
@ -130,6 +131,52 @@ routes['file'] = (req, res) => {
|
|||
});
|
||||
}
|
||||
|
||||
routes['upload'] = (req, res) => {
|
||||
if (req.method != 'GET' && req.method != 'POST') {
|
||||
error(res, 405, 'Use this URL with only GET or POST requests');
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.method == 'POST') {
|
||||
const form = new formidable.IncomingForm();
|
||||
form.uploadDir = __dirname + '/NodeStaticFiles';
|
||||
form.keepExtensions = true;
|
||||
|
||||
form.parse(req);
|
||||
|
||||
form.on('fileBegin', (name, file) => {
|
||||
file.path = file.path.substring(0, file.path.lastIndexOf('/') + 1);
|
||||
file.path += file.name;
|
||||
});
|
||||
form.on('end', () => {
|
||||
res.writeHead(302, { 'Location': '/explore' });
|
||||
res.end();
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
res.writeHead(200, { 'Content-Type': 'text/html' });
|
||||
res.end(`<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Upload</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Upload</h1>
|
||||
<form id="upload-form" enctype="multipart/form-data" method="post">
|
||||
<label for="file">File:</label>
|
||||
<input type="file" name="file"><br>
|
||||
<input type="submit" name="submit" value="Submit">
|
||||
</form>
|
||||
</body>
|
||||
</html>`);
|
||||
};
|
||||
|
||||
routes['stats'] = (req, res) => {
|
||||
res.end()
|
||||
};
|
||||
|
||||
// Main server handler
|
||||
function onRequest(req, res) {
|
||||
|
|
Reference in a new issue