uploader / main.coffee
SaengChu2's picture
Update main.coffee
7f7055d verified
fs = require 'fs'
os = require 'os'
bytes = require 'bytes'
cors = require 'cors'
express = require 'express'
{ fromBuffer } = require 'file-type'
multer = require 'multer'
archiver = require 'archiver'
limitSize = '5000mb'
tmpFolder = os.tmpdir()
app = express()
app.set 'json spaces', 4
app.use cors()
# limit upload file
app.use express.json limit: limitSize
app.use express.urlencoded extended: true, limit: limitSize
# multer configuration
upload = multer({ dest: tmpFolder })
# logger
app.use (req, res, next) ->
time = new Date().toLocaleString 'id', timeZone: 'Asia/Jakarta'
console.log "[#{time}] #{req.method}: #{req.url}"
next()
# allow user to access file in tmpFolder
app.use '/file', express.static tmpFolder
app.all '/', (_, res) ->
res.send """
<!doctype html>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<h1>Upload a file</h1>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<button type="submit">Upload</button>
</form>
</body>
</html>
"""
app.post '/upload', upload.single('file'), (req, res) ->
do ->
return res.json(message: 'No file uploaded') unless req.file
fileBuffer = fs.readFileSync req.file.path
ftype = await fromBuffer fileBuffer
ftype = { mime: 'file', ext: 'bin' } unless ftype
randomName = Math.random().toString(36).slice(2)
fileName = "#{ftype.mime.split('/')[0]}-#{randomName}.#{ftype.ext}"
await fs.promises.rename req.file.path, "#{tmpFolder}/#{fileName}"
res.json
name: fileName
size:
bytes: fileBuffer.length
readable: bytes(fileBuffer.length, unitSeparator: ' ')
type: ftype
url: "https://#{process.env.SPACE_HOST}/file/#{fileName}"
# Endpoint to download a zip file containing files from the tmp folder
app.get '/download-zip', (req, res) ->
do ->
archive = archiver 'zip', zlib: level: 9
res.attachment 'files.zip'
archive.on 'error', (err) ->
throw err
archive.pipe res
# Add files from tmp folder to the zip
fs.readdir tmpFolder, (err, files) ->
return res.status(500).send 'Could not list the directory.' if err
files.forEach (file) ->
filePath = "#{tmpFolder}/#{file}"
archive.file filePath, name: file
archive.finalize()
app.listen 7860, -> console.log 'App running on port', 7860