Can't upload file by form data in Heroku

226 views Asked by At

I am using multipart/form-data to send file from client to NodeJS server. In BE I using multer for save image. Every things is fine when i run my app in localhost. But after deploy to heroku, i cannot upload file and an error message is logged:

TypeError: Cannot read properties of undefined (reading 'filename')

Here is my back end code:

  1. upload controller
const createNewCV = async (req, res) => {
  uploadCVFile.single("cvFile")(req, res, (err) => {
    let message;
    const userData = req.body;
    if (err instanceof multer.MulterError) {
      message = "fail to upload cv file!";
      res.status(200).json({ success: false, message: message }); 

    }
    try {
      const link = `${DEFAULT_CV_PATH}${req.file.filename}`;  //req.file is undefined
      res.status(200).json({ success: true });
    } catch (error) {
      console.log(error);
      return null;
    }
  });
};
  1. Uploads service:
const storageFile = (folderPath) =>
  multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, folderPath);
    },
    filename: function (req, file, cb) {
      const uniqueSuffix = randomUnixSuffix() + path.extname(file.originalname);
      cb(null, file.originalname.split(".")[0] + "-" + uniqueSuffix);
    },
  });

const uploadCVFile = multer({ storage: storageFile(CV_FOLDER_PATH) });

module.exports = { uploadCVFile};

This is my uploads folder in BE: enter image description here

0

There are 0 answers