import { connectToDb, fileExists } from "@/lib/mongodb";
import { NextResponse } from "next/server";
import { Readable } from "stream";
import formidable, { errors as formidableErrors } from 'formidable';
var fs = require('fs');
var md5 = require('md5');
export const config = {
api: {
bodyParser: false,
}
};
type ProcessedFiles = Array<[string, File]>;
export default async function handler(req: any, res: any) {
const { bucket } = await connectToDb();
// get the form data
// const data = await req.formData();
// Access uploaded files directly using req.files
//const files = Array.from(req.files.entries());
let status = 200,
resultBody = { status: 'ok', message: 'Files were uploaded successfully' };
const form = formidable({ uploadDir: "/tmp" });
let fields;
let files;
try {
form.parse(req, async (err, fields, files) => {
console.log('fields:', fields);
console.log('files:', files);
for (const [key, value] of Object.entries(files)) {
const isFile = typeof value == "object";
if (isFile) {
let file: any = value[0]
let filename = file.originalFilename
let type = file.mimetype
let buffer = fs.readFileSync(file.filepath);
const stream = Readable.from(buffer);
const hash = md5(buffer)
const existing = await fileExists(hash);
if (existing) {
// If file already exists, let's skip it.
// If you want a different behavior such as override, modify this part.
continue;
}
const uploadStream = bucket.openUploadStream(filename, {
// make sure to add content type so that it will be easier to set later.
contentType: type,
metadata: {
hash:hash
}, //add your metadata here if any
});
// pipe the readable stream to a writeable stream to save it to the database
await stream.pipe(uploadStream);
res.status(200).json({
hash: hash
})
}
}
});
} catch (err: any) {
// example to check for a very specific error
if (err.code === formidableErrors.maxFieldsExceeded) {
}
console.error(err);
res.writeHead(err.httpCode || 400, { 'Content-Type': 'text/plain' });
res.end(String(err));
return;
}
return res.json({ success: true });
}