0

I am using multer to upload the file using the nextjs. In nextjs, I have created a folder "auth" inside "api" folder. So my API path will be 'http://localhost:300/api/auth/post'.

Now I am using "next-connector" library along with multer to upload the file. The code runs successfully without any errors. But when I try to run with postman or directly from the frontend, I am getting the error of "Unexpected end of form" in postman.

Here is my code: file name post.js

import multer from "multer";
import path from "path";
import fs from "fs";
import { NextApiRequest, NextApiResponse } from "next";
import nextConnect from "next-connect";

const handler = nextConnect({
  onNoMatch(req, res) {
    res.status(405).json({ error: `Method '${req.method}' Not Allowed` });
  },
});

const postStorage = multer.diskStorage({
  destination: (req, file, cb) => {
    console.log("inside destination in multer");
    // const folderName = path.join(__dirname, "..", "public");

    // if (fs.existsSync(folderName)) {
    //   cb(null, folderName);
    // } else {
    //   fs.mkdirSync(folderName);

    //   cb(null, folderName);
    // }
    cb(null, "/upload");
  },
  filename: (req, file, cb) => {
    console.log("req.file inside filename param", req.file);
    const flieName = Date.now() + file.mimetype.split("/")[1];

    cb(null, flieName);
  },
});

export const uploadPost = multer({
  storage: postStorage,
  fileFilter: (req, file, cb) => {
    console.log("inside file filter");
    if (
      file.mimetype != "image/png" ||
      file.mimetype != "image/jpeg" ||
      file.mimetype != "image/jpg" ||
      file.mimetype != "video/mp4"
    ) {
      cb(null, false, "Something went wrong wjt tablet");
    } else {
      cb(null, true);
    }
  },
});

const uploadFile = uploadPost.single("postImage");

handler.use(uploadFile);

handler.post((req, res) => {
  console.log("body and file", req.body, req.file);
  res.json({ code: 200, success: true });
});

export default handler;

export const config = {
  api: {
    bodyParser: {
      sizeLimit: "4mb", // Set desired value here
    },
  },
};

Jayna Tanawala
  • 475
  • 10
  • 27

0 Answers0