-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
43 lines (33 loc) · 1.35 KB
/
index.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
const fastify = require('fastify')({ logger: true, bodyLimit: 9999999 })
const fastifyMultipart = require('@fastify/multipart')
const path = require('path')
const fs = require('fs')
fastify.register(fastifyMultipart, { attachFieldsToBody: true, limits: 9999999 })
fastify.post('/upload', async (req, res) => {
// Access uploaded files using field names
const file = await req.body.file.toBuffer()
// Process the files as needed
// ...
fs.writeFile(path.join(__dirname, 'static/uploads', req.body.file.filename), await req.body.file.toBuffer(), (err, data) => {
if(err) return res.code(500).send('error')
else return
});
})
fastify.register(require('@fastify/static'), { root: path.join(__dirname, 'static') });
fastify.get('/uploads/:id', (req, res) => {
fs.access(path.join(__dirname, 'static/uploads', req.params.id), err => {
if(err) console.error(err)
if(err) return res.code(404).send('no file found')
else{
res.header('Content-Disposition', 'attachment; filename=' + req.params.id);
return res.sendFile('uploads/' + req.params.id);
}
})
})
fastify.listen({ port: 80, host: "0.0.0.0" }, (err, address) => {
if (err) {
fastify.log.error(err)
process.exit(1)
}
console.log(`Server is now listening on ${address}`)
})