48 lines
No EOL
1.1 KiB
TypeScript
48 lines
No EOL
1.1 KiB
TypeScript
import multer from 'multer';
|
|
import type { Options } from 'multer';
|
|
import fs from 'fs';
|
|
import { v4 } from 'uuid';
|
|
|
|
export const uploadService = () => {
|
|
let folderPath = process.env.NODE_ENV == 'development' ? './src/public/' : './public/';
|
|
if (!fs.existsSync(folderPath)) {
|
|
fs.mkdirSync(folderPath, { recursive: true })
|
|
}
|
|
const { limits: templateLimits }: Options = {
|
|
limits: {
|
|
files: 1,
|
|
fieldNameSize: 400,
|
|
fileSize: 80 * 1024 * 1024,
|
|
},
|
|
};
|
|
|
|
const { filename }: multer.DiskStorageOptions = {
|
|
filename: (_req, file, cb) => {
|
|
const splittedFileName = file.originalname.split('.');
|
|
let name = splittedFileName[0];
|
|
const type = splittedFileName[1];
|
|
name += '-' + v4().slice(0, 5) + '.' + type;
|
|
cb(null, name);
|
|
},
|
|
};
|
|
|
|
const generateHandler = () => {
|
|
try {
|
|
const options: Options = {
|
|
limits: {
|
|
...templateLimits,
|
|
},
|
|
storage: multer.diskStorage({
|
|
filename,
|
|
destination: folderPath
|
|
}),
|
|
};
|
|
|
|
return multer(options).single('imgs');
|
|
} catch (e) {
|
|
console.error('Upload error', e)
|
|
throw e;
|
|
}
|
|
};
|
|
return { generateHandler };
|
|
}; |