Jonatan Nilsson
58553f3e34
Breaking: Renamed name to filename when listing files in folder. Breaking: Fixed the schema response for /media/resize. It is now consistent with other upload methods.
58 lines
1.6 KiB
JavaScript
58 lines
1.6 KiB
JavaScript
import fs from 'fs'
|
|
import { HttpError } from '../error.mjs'
|
|
import formidable from 'formidable'
|
|
import config from '../config.mjs'
|
|
|
|
let lastDateString = ''
|
|
let incrementor = 1
|
|
|
|
export function uploadFile(ctx, siteName, noprefix = false) {
|
|
return new Promise((res, rej) => {
|
|
const date = new Date()
|
|
|
|
let prefix = ''
|
|
|
|
if (!noprefix) {
|
|
// Generate 'YYYYMMDD_HHMMSS_' prefix
|
|
prefix = date
|
|
.toISOString()
|
|
.replace(/-/g, '')
|
|
.replace('T', '_')
|
|
.replace(/:/g, '')
|
|
.replace(/\..+/, '_')
|
|
|
|
// Append xx_ if same date is hit multiple times
|
|
if (prefix === lastDateString) {
|
|
prefix += incrementor.toString().padStart('2', '0') + '_'
|
|
incrementor++
|
|
} else {
|
|
lastDateString = prefix
|
|
}
|
|
}
|
|
|
|
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
|
|
|
|
Object.keys(fields).forEach(function(key) {
|
|
try {
|
|
fields[key] = JSON.parse(fields[key])
|
|
} catch { }
|
|
})
|
|
ctx.req.body = fields
|
|
|
|
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)
|
|
})
|
|
})
|
|
})
|
|
}
|