Upload 2 files
Browse files- main.coffee +56 -0
- package (2).json +6 -0
main.coffee
ADDED
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
fs = require 'fs'
|
2 |
+
os = require 'os'
|
3 |
+
bytes = require 'bytes'
|
4 |
+
express = require 'express'
|
5 |
+
{ fromBuffer } = require 'file-type'
|
6 |
+
|
7 |
+
limitSize = '500mb'
|
8 |
+
tmpFolder = os.tmpdir()
|
9 |
+
|
10 |
+
isBase64 = (str) ->
|
11 |
+
try
|
12 |
+
btoa(atob(str)) is str
|
13 |
+
catch
|
14 |
+
false
|
15 |
+
|
16 |
+
app = express()
|
17 |
+
app.set 'json spaces', 4
|
18 |
+
# limit upload file
|
19 |
+
app.use express.json limit: limitSize
|
20 |
+
app.use express.urlencoded extended: true, limit: limitSize
|
21 |
+
# logger
|
22 |
+
app.use (req, res, next) ->
|
23 |
+
time = new Date().toLocaleString 'id', timeZone: 'Asia/Jakarta'
|
24 |
+
console.log "[#{time}] #{req.method}: #{req.url}"
|
25 |
+
next()
|
26 |
+
# allow user to access file in tmpFolder
|
27 |
+
app.use '/file', express.static tmpFolder
|
28 |
+
|
29 |
+
app.all '/', (_, res) -> res.send 'POST /upload'
|
30 |
+
|
31 |
+
app.all '/upload', (req, res) ->
|
32 |
+
if req.method isnt 'POST'
|
33 |
+
res.json message: 'Method not allowed'
|
34 |
+
|
35 |
+
{ file } = req.body
|
36 |
+
if not file and typeof file isnt 'string' and not isBase64 file
|
37 |
+
res.json message: 'Payload body file must be filled in base64 format'
|
38 |
+
|
39 |
+
fileBuffer = Buffer.from file, 'base64'
|
40 |
+
ftype = await fromBuffer fileBuffer
|
41 |
+
if not ftype then ftype = mime: 'file', ext: 'bin'
|
42 |
+
|
43 |
+
randomName = Math.random().toString(36).slice(2)
|
44 |
+
fileName = "#{ftype.mime.split('/')[0]}-#{randomName}.#{ftype.ext}"
|
45 |
+
await fs.promises.writeFile "#{tmpFolder}/#{fileName}", fileBuffer
|
46 |
+
|
47 |
+
res.json
|
48 |
+
name: fileName,
|
49 |
+
size:
|
50 |
+
bytes: fileBuffer.length,
|
51 |
+
readable: bytes fileBuffer.length, unitSeparator: ' '
|
52 |
+
,
|
53 |
+
type: ftype,
|
54 |
+
url: "https://#{process.env.SPACE_HOST}/file/#{fileName}"
|
55 |
+
|
56 |
+
app.listen 7860, () -> console.log 'App running on port', 7860
|
package (2).json
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"dependencies": {
|
3 |
+
"express": "^4.18.2",
|
4 |
+
"file-type": "^16.5.4"
|
5 |
+
}
|
6 |
+
}
|