| 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 | |
| } | |
| } |