0

I have used the following code. I can send it successfully to my server folder on my computer (process.env.CV.DIR) but I can't get the path to sent to the database. I can see the filename on the browser and I can see it in the server folder if I check manually. If I console.log my server folder, I get an object , for example, myCvs : PersistentFile{ }, filename:

But I can't access filename. If I do a console.log of process.env.CV.DIR I get to myCvs but if I console.log process.env.CV.DIR.myCvs.filename, I get undefined

 ```   import type { NextApiHandler, NextApiRequest } from 'next';
import formidable from 'formidable';
import path from 'path';
import fs from 'fs/promises';
import prisma from '../../../../lib/prisma';

export const config = {
  api: {
    bodyParser: false,
  },
};
const readFile = (
  req: NextApiRequest,
  saveLocally?: boolean
): Promise<{ fields: formidable.Fields; files: formidable.Files }> => {
  const options: formidable.Options = {};
  if (saveLocally) {
    options.uploadDir = process.env.CV_DIR;
    options.filename = (name, ext, path, form) => {
      return Date.now().toString() + '_' + path.originalFilename;
    };
  }
  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 });
      console.log('fields => ', fields);
      console.log('files => ', `${process.env.CV_DIR}`);
      const file = files.myCv;
    });
  });
};

const handler: NextApiHandler = async (req, res) => {

  try {
    await fs.readdir(process.env.CV_DIR);
  } catch (error) {
    console.log('error uploading cv to server');
  }
  await readFile(req, true);
  res.json({ done: 'ok' });
 };
export default handler;
function getPath(arg0: string): any {
  throw new Error('Function not implemented.');
}```
Tony
  • 5
  • 3
  • Does this answer your question? [Get file name from absolute path in Nodejs?](https://stackoverflow.com/questions/19811541/get-file-name-from-absolute-path-in-nodejs) – Yilmaz Apr 04 '23 at 17:54

0 Answers0