import { NextApiHandler, NextApiRequest } from "next";
import formidable from "formidable";
import path from "path";
import fs from "fs/promises";
import {randomUUID} from "crypto";
export const config = {
api: {
bodyParser: false,
},
};
const readFile = (
req: NextApiRequest,
filename: string,
saveLocally?: boolean
): Promise<{ fields: formidable.Fields; files: formidable.Files }> => {
const options: formidable.Options = {};
if (saveLocally) {
options.uploadDir = path.join(process.env.RAILWAY_VOLUME_MOUNT_PATH, "/uploads");
options.filename = (name, ext, path, form) => {
const extension = path.originalFilename?.split(".")[1];
return `${filename}.${extension}`;
};
}
options.maxFileSize = 4000 * 1024 * 1024;
const form = formidable(options);
return new Promise((resolve, reject) => {
form.parse(req, (err, fields, files) => {
if (err) reject(err);
resolve({ fields, files });
});
});
};
const handler: NextApiHandler = async (req, res) => {
try {
// await fs.readdir(path.join(process.cwd() + "/public", "/upload_images"));
await fs.readdir(path.join(process.env.RAILWAY_VOLUME_MOUNT_PATH, "/uploads"));
} catch (error) {
// await fs.mkdir(path.join(process.cwd() + "/public", "/upload_images"));
await fs.mkdir(path.join(process.env.RAILWAY_VOLUME_MOUNT_PATH, "/uploads"));
}
const filename = randomUUID();
const { files } = await readFile(req, filename, true);
// @ts-ignore
const extension = files.image[0]?.newFilename.split('.')[1];
res.json({ done: "ok", filename: `${filename}.${extension}` });
};
export default handler;