How to send file in form data in Next Js?

Viewed 1940

I have created an API in Node js for file upload. It is working fine with the postman.

I made a form for uploading Excel files in Next Js. I can able to see selected files in the console.

But I am not able to set the file in formdata. I am getting empty form data in the console.

<div>
        <input
          class="form-control w-25"
          multiple={false}
          type="file"
          id="ExcelFile"
          onChange={uploadFile}
          required
        ></input>
        {/* </label> */}
        <button
          type="button"
          // disabled={!selectedImage}
          class="btn btn-primary "
        >
          ADD SOLUTION
        </button>
      </div>

const uploadFile = ({ target: { files } }) => {
    console.log(files[0]);
    // let data = new formData();
    let FilesData = new FormData();
    FilesData.append("excel_file", files[0]);
    console.log("Files in multipart");
    console.log(FilesData);
    // data.append("file", files[0]);
  };

https://codesandbox.io/embed/next-js-forked-th22n?fontsize=14&hidenavigation=1&theme=dark

3 Answers

If you try to console.log FormData object, you will just get empty object.Instead you should call the entries method on the FormData object.

for (const pair of FilesData.entries()){
  console.log(pair)
}

It will return list of arrays of key-value pairs.

Notice that you can`t see your formData in console.log If you want to pass data with formData you must use one middleware in your server like this: https://nextjs.org/docs/api-routes/api-middlewares And i just use one example maybe be usefull: in your formData:

var FormData = require("form-data");

let data = new FormData()
data.append("urlOrContent", urlOrContent)

and then send your formData in your server side in your server side:

import middleware from "./middleware/middleware";

import nextConnect from "next-connect";

const handler = nextConnect();
handler.use(middleware);

handler.post(async (req, res) => {
//in formData: req.body.urlOrcontent[0]
  try {
    const response = await fetch(
      req.body?.urlOrContent[0],
    );
    res.status(200).send({
      data: {
        message: "Success",
        data: response.json(),
      },
    });
  } catch (err) {
    let e = {
      func: "states.handler",
      message: "خطای داخلی سرور رخ داده است!",
      error: "Internal Server Error!",
      code: 500,
    };
    res.status(500).json(e);
  }
});

export const config = {
  api: {
    bodyParser: false,
  },
};
export default handler;

Here's a little example on a simple form submission in next.js using multer to parse the form data.

Client

This is the client page, containing a super simple HTML form (can work without JS too)

// pages/my-form.ts

export default function Page() {
  return (
    <div>
      <form id="data" method="post" action='/api/on-form-submit' encType="multipart/form-data">
        <input name="title" label="Title"/>
        <input name="video" label="Video"/>

        <button type="submit">Submit</button>
      </form>
    </div>
  );
};

Server

This is the server function that will receive the form submission.

// pages/api/on-form-submit.ts

import multer from "multer";
import { NextApiRequest, NextApiResponse } from "next";

async function parseFormData(
  req: NextApiRequest & { files?: any },
  res: NextApiResponse
) {
  const storage = multer.memoryStorage();
  const multerUpload = multer({ storage });
  const multerFiles = multerUpload.any();
  await new Promise((resolve, reject) => {
    multerFiles(req as any, res as any, (result: any) => {
      if (result instanceof Error) {
        return reject(result);
      }
      return resolve(result);
    });
  });
  return {
    fields: req.body,
    files: req.files
  }
}

// IMPORTANT: Prevents next from trying to parse the form
export const config = {
  api: {
    bodyParser: false,
  },
};

const Handler: NextApiHandler = async (req, res) => {
  const result = await parseFormData(req, res);
  console.log(result);
  res.status(200).redirect('/success-page');
}
export default Handler;
Related