uploader / index.js
akkun3704's picture
Create index.js
f8cd941
raw
history blame
1.34 kB
import fs from 'fs'
import bytes from 'bytes'
import express from 'express'
import { fileTypeFromBuffer } from 'file-type'
const app = 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'))
.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]}-${Math.random().toString(36).slice(2)}.${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://${process.env.SPACE_HOST}/file/${fileName}`
})
})
.listen(7860, () => console.log('App running\n', app))
function isBase64(str) {
try {
return btoa(atob(str)) === str
} catch {
return false
}
}