From 50d194ac2d8a67f19632b90fb220ece745e81dc1 Mon Sep 17 00:00:00 2001 From: "Claudio Maggioni (maggicl)" Date: Sat, 12 Oct 2019 14:59:32 +0200 Subject: [PATCH] hw4: ex4 passes tests --- hw4/Claudio_Maggioni/server.js | 53 ++++++++++++++++++++++++++++++++-- 1 file changed, 50 insertions(+), 3 deletions(-) diff --git a/hw4/Claudio_Maggioni/server.js b/hw4/Claudio_Maggioni/server.js index dabb55d..e26f508 100755 --- a/hw4/Claudio_Maggioni/server.js +++ b/hw4/Claudio_Maggioni/server.js @@ -1,9 +1,10 @@ #!/usr/bin/env node // vim: set ts=2 sw=2 et tw=80: -const http = require('http'); -const url = require('url'); -const fs = require('fs'); +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(` + + + + Upload + + +

Upload

+
+ +
+ +
+ + `); +}; + +routes['stats'] = (req, res) => { + res.end() +}; // Main server handler function onRequest(req, res) {