46 lines
1 KiB
TypeScript
46 lines
1 KiB
TypeScript
import multer from 'multer'
|
|
import type { Options } from 'multer'
|
|
import fs from 'fs'
|
|
import { v4 } from 'uuid'
|
|
import path from 'path'
|
|
|
|
export const uploadService = () => {
|
|
let folderPath = './server/public/images/'
|
|
if (!fs.existsSync(folderPath)) {
|
|
fs.mkdirSync(folderPath, { recursive: true })
|
|
}
|
|
const { limits: templateLimits }: Options = {
|
|
limits: {
|
|
files: 10,
|
|
fieldNameSize: 400,
|
|
fileSize: 800 * 1024 * 1024,
|
|
},
|
|
};
|
|
|
|
const { filename }: multer.DiskStorageOptions = {
|
|
filename: (_req, file, cb: Function) => {
|
|
const type = path.extname(file.originalname)
|
|
cb(null, v4() + type)
|
|
}
|
|
}
|
|
|
|
const generateHandler = () => {
|
|
try {
|
|
const options: Options = {
|
|
limits: {
|
|
...templateLimits,
|
|
},
|
|
storage: multer.diskStorage({
|
|
filename,
|
|
destination: folderPath
|
|
}),
|
|
};
|
|
|
|
return multer(options).array('images', 10);
|
|
} catch (e) {
|
|
console.error('Upload error', e)
|
|
throw e;
|
|
}
|
|
};
|
|
return { generateHandler };
|
|
};
|