file.ts
1011 Bytes
import { join, extname } from 'path'
import { diskStorage } from 'multer'
import * as fs from 'fs'
const normalizeName = (originalname: string) => {
const ext = extname(originalname)
const base = originalname.slice(0, originalname.length - ext.length)
return base.replace(/_\d{10,}$/, '').replace(/@\d+@\d{10,}(?:-\d+)?$/, '')
}
export default {
root: join(__dirname, '..', '..', process.env.STATIC_PATH),
storage: diskStorage({
destination: (req, file, cb) => {
const now = new Date()
const year = now.getFullYear()
const month = now.getMonth() + 1
const target = join(__dirname, '..', '..', `${process.env.STATIC_PATH}/${year}/${month}`)
fs.mkdirSync(target, { recursive: true })
return cb(null, target)
},
filename: (req, file, cb) => {
const deviceId = req.body.deviceId
const name = normalizeName(file.originalname)
const filename = `${name}@${deviceId}${extname(file.originalname)}`
return cb(null, filename)
}
})
}