File size: 1,565 Bytes
f8cd941
 
 
 
 
95f2edb
4ab1192
f8cd941
 
 
 
 
95f2edb
deb32f4
 
 
95f2edb
 
f8cd941
 
 
 
 
 
 
 
 
95f2edb
f8cd941
 
 
 
 
 
 
 
 
95f2edb
f8cd941
 
4ab1192
f8cd941
 
 
 
 
 
 
95f2edb
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
import fs from 'fs'
import bytes from 'bytes'
import express from 'express'
import { fileTypeFromBuffer } from 'file-type'

const { SPACE_HOST } = process.env
express()
	.set('json spaces', 4)
	.use(express.json({ limit: '500mb' }))
	.use(express.urlencoded({ extended: true, limit: '500mb' }))
	.all('/', (_, res) => res.send('POST /upload'))
	.use('/file', express.static('/tmp'))
	.get(['/list', '/files'], (_, res) => {
		const files = fs.readdirSync('/tmp', { withFileTypes: true })
			.filter(file => file.isFile())
			.map(file => `https://${SPACE_HOST}/file/${file.name}`)
		res.send(files)
	})
	.all('/upload', async (req, res) => {
		if (req.method !== 'POST') return res.json({ message: 'Method not allowed' })
		
		const { file } = req.body
		if (!file && typeof file !== 'string' && !isBase64(file))
			return res.json({ message: 'Payload body file must be filled in base64 format' })
		
		const fileBuffer = Buffer.from(file, 'base64')
		const ftype = await fileTypeFromBuffer(fileBuffer) || { mime: 'file', ext: 'bin' }
		const fileName = `${ftype.mime.split('/')[0]}-${Date.now().toString(16)}.${ftype.ext}`
		await fs.promises.writeFile(`/tmp/${fileName}`, fileBuffer)
		
		res.json({
			name: fileName,
			size: {
				bytes: fileBuffer.length,
				readable: bytes(+fileBuffer.length, { unitSeparator: ' ' })
			},
			type: ftype,
			url: `https://${SPACE_HOST}/file/${fileName}`
		})
	})
	.listen(7860, () => console.log('App running on port', 7860))

function isBase64(str) {
	try {
		return btoa(atob(str)) === str
	} catch {
		return false
	}
}