Create index.js
Browse files
index.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import fs from 'fs'
|
| 2 |
+
import bytes from 'bytes'
|
| 3 |
+
import express from 'express'
|
| 4 |
+
import { fileTypeFromBuffer } from 'file-type'
|
| 5 |
+
|
| 6 |
+
const app = express()
|
| 7 |
+
.set('json spaces', 4)
|
| 8 |
+
.use(express.json({ limit: '500mb' }))
|
| 9 |
+
.use(express.urlencoded({ extended: true, limit: '500mb' }))
|
| 10 |
+
.all('/', (_, res) => res.send('POST /upload'))
|
| 11 |
+
.use('/file', express.static('/tmp'))
|
| 12 |
+
.all('/upload', async (req, res) => {
|
| 13 |
+
if (req.method !== 'POST') return res.json({ message: 'Method not allowed' })
|
| 14 |
+
|
| 15 |
+
const { file } = req.body
|
| 16 |
+
if (!file && typeof file !== 'string' && !isBase64(file))
|
| 17 |
+
return res.json({ message: 'Payload body file must be filled in base64 format' })
|
| 18 |
+
|
| 19 |
+
const fileBuffer = Buffer.from(file, 'base64')
|
| 20 |
+
const ftype = await fileTypeFromBuffer(fileBuffer) || { mime: 'file', ext: 'bin' }
|
| 21 |
+
const fileName = `${ftype.mime.split('/')[0]}-${Math.random().toString(36).slice(2)}.${ftype.ext}`
|
| 22 |
+
await fs.promises.writeFile(`/tmp/${fileName}`, fileBuffer)
|
| 23 |
+
|
| 24 |
+
res.json({
|
| 25 |
+
name: fileName,
|
| 26 |
+
size: {
|
| 27 |
+
bytes: fileBuffer.length,
|
| 28 |
+
readable: bytes(+fileBuffer.length, { unitSeparator: ' ' })
|
| 29 |
+
},
|
| 30 |
+
type: ftype,
|
| 31 |
+
url: `https://${process.env.SPACE_HOST}/file/${fileName}`
|
| 32 |
+
})
|
| 33 |
+
})
|
| 34 |
+
.listen(7860, () => console.log('App running\n', app))
|
| 35 |
+
|
| 36 |
+
function isBase64(str) {
|
| 37 |
+
try {
|
| 38 |
+
return btoa(atob(str)) === str
|
| 39 |
+
} catch {
|
| 40 |
+
return false
|
| 41 |
+
}
|
| 42 |
+
}
|