import fs from 'fs' import { HttpError } from '../error.mjs' import formidable from 'formidable' import config from '../config.mjs' export function uploadFile(ctx, siteName) { return new Promise((res, rej) => { const date = new Date() // Generate 'YYYYMMDD_HHMMSS_' prefix const prefix = date .toISOString() .replace(/-/g, '') .replace('T', '_') .replace(/:/g, '') .replace(/\..+/, '_') var form = new formidable.IncomingForm() form.uploadDir = `./public/${siteName}` form.maxFileSize = config.get('fileSize') form.parse(ctx.req, function(err, fields, files) { if (err) return rej(err) if (!files || !files.file) return rej(new HttpError('File in body was missing', 422)) let file = files.file fs.rename(files.file.path, `./public/${siteName}/${prefix}${file.name}`, function(err) { if (err) return rej(err) file.path = `./public/${siteName}/${prefix}${file.name}` file.filename = `${prefix}${file.name}` return res(file) }) }) }) }