node/zad2.js

51 lines
1.4 KiB
JavaScript
Raw Normal View History

2019-06-14 19:23:04 +02:00
const express = require('express');
const multer = require('multer');
const fs = require('fs');
const app = express();
const PORT = 49376;
const UPLOAD_DIRECTORY = './uploads';
const upload = multer({
storage: multer.diskStorage({
destination: (req, file, cb) => { cb(null, UPLOAD_DIRECTORY); },
filename: (req, file, cb) => { cb(null, file.originalname); }
})
}).single('file');
app.get('/', (req, res) => {
res.type('html');
fs.readdir(UPLOAD_DIRECTORY, (err, items) => {
var up = '';
for (var i = 0; i < items.length; i++) {
up += `<li><a href="/${items[i]}">${items[i]}</a></li>`;
}
up = up || 'There are no uploaded files...';
res.end(`
<h3>Upload form</h3>
<form action="/" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="send" name="submit">
</form>
<h3>Files to download</h3>
<ul>${up}</ul>
`);
});
});
app.post('/', (req, res) => {
upload(req, res, (err) => {
if (err) { res.end('Error!'); }
else { res.redirect('/'); }
});
});
app.get('/:file(*)', (req, res) => {
res.download(UPLOAD_DIRECTORY + '/' + req.params.file, req.params.file);
});
app.listen(PORT, () => {
console.log(`Listening at http://localhost:${PORT}/`);
});