-
Notifications
You must be signed in to change notification settings - Fork 0
/
koa.js
52 lines (47 loc) · 1.53 KB
/
koa.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
const Koa = require('koa');
const cors = require('koa2-cors');
const bodyParser = require('koa-bodyparser');
const fs = require('fs');
const path = require('path');
const multer = require('@koa/multer');
const app = new Koa();
const port = 4000;
app.use(cors());
app.use(bodyParser());
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, path.join(__dirname, 'storage'));
},
filename: (req, file, cb) => {
const uniqueName = file.originalname + '.pdf';
cb(null, uniqueName);
}
});
const upload = multer({ storage });
app.use(upload.single('file'));
app.use(async (ctx, next) => {
if (ctx.path.startsWith('/download/')) {
const archivoNombre = ctx.path.replace('/download/', '');
const archivoRuta = path.join(__dirname, 'storage', archivoNombre);
try {
const stat = fs.statSync(archivoRuta);
ctx.attachment(archivoNombre);
ctx.set('Content-Type', 'application/octet-stream');
ctx.set('Content-Length', stat.size);
ctx.body = fs.createReadStream(archivoRuta);
} catch (error) {
ctx.status = 404;
ctx.body = error;
}
} else if (ctx.path.startsWith('/upload')) {
await upload.single('file')(ctx, next);
const uploadedFile = ctx.file;
console.log(uploadedFile);
ctx.body = 'Archivo subido';
} else {
await next();
}
});
app.listen(port, () => {
console.log(`Servidor Koa escuchando en el puerto ${port}`);
});