Multer 不使用 next-connect 返回 req.body 和 req.file

Eye*_*tch 4 middleware node.js multer next.js next-connect

我正在使用 nextjs,我想上传一个文件,所以我使用 next-connect 来使用 multer

import nc from "next-connect";
import multer from "multer";

export const config = {
    api: {
      bodyParser: false,
    },
}

const upload = multer({ dest: `${__dirname}../../public` });

const handler = nc()
  .use(upload.single('image'))
  .post(async (req, res)=>{
    console.log(req.body); // undefined
    console.log(req.file); // undefined
    res.status(200).send("yo");
  })


export default handler;
Run Code Online (Sandbox Code Playgroud)

这是客户端代码:

function handleOnSubmit(e){
        e.preventDefault();

        const data = {};

        var formData = new FormData(e.target);
        for (const [name,value] of formData) {
            data[name] = value;
        }
        data.type = data.type[0].toUpperCase();
        data.name = data.name[0].toUpperCase();

        axios({
            method: "POST",
            url:"/api/manager",
            data,
            config: {
                headers: {
                    'content-type': 'multipart/form-data'
                }
            }
        })
        .then(res=>{
            console.log(res);
        })
        .catch(err=>{
            throw err
        });
    }
...
return(
   ...
   <Form onSubmit={(e)=>handleOnSubmit(e)}>
   ...
   </Form>
)
Run Code Online (Sandbox Code Playgroud)

我进行了搜索,发现的所有内容都与 Nodejs 和 ExpressJS 相关,但没有与 next.js 相关。我不知道如何继续。

Jer*_*me 9

对于那些仍在寻找如何将 multer 用作 nextJs 中间件的解决方案的人,这里是一个 API 路线的示例,使用 multer 有中间件。该路由正在调用 getSignedUrl 函数将文件上传到存储桶。

运行 nextJs v12 和 multer 1.4.3

import multer from "multer";
import { NextApiRequest, NextApiResponse } from "next";
import { getSignedUrl } from "../../lib/uploadingToBucket";

function runMiddleware(
  req: NextApiRequest & { [key: string]: any },
  res: NextApiResponse,
  fn: (...args: any[]) => void
): Promise<any> {
  return new Promise((resolve, reject) => {
    fn(req, res, (result: any) => {
      if (result instanceof Error) {
        return reject(result);
      }

      return resolve(result);
    });
  });
}

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

const handler = async (
  req: NextApiRequest & { [key: string]: any },
  res: NextApiResponse
): Promise<void> => {
  //const multerStorage = multer.memoryStorage();
  const multerUpload = multer({ dest: "uploads/" });

  await runMiddleware(req, res, multerUpload.single("file"));
  const file = req.file;
  const others = req.body;
  const signedUrl = await getSignedUrl(others.bucketName, file.filename);
   res.status(200).json({ getSignedUrl: signedUrl });
};

export default handler;
Run Code Online (Sandbox Code Playgroud)

  • 看来 multer 不是 next.js 最好的朋友。 (3认同)

小智 7

当我切换到 Next.js 框架时,我首先尝试使用“multer”库上传文件,但宁愿放弃并使用“formidable”。原因是 Nextjs 和 multer 有一些可用的资源。

如果我没记错的话,multer 应该作为中间件添加,所以这意味着重写 server.js 页面。您可以查看这些主题:

如果您不想处理这个问题,您可以查看使用这个强大的资源库的简单要点:https://gist.github.com/agmm/da47a027f3d73870020a5102388dd820

这是我创建的文件上传脚本:https://github.com/fatiiates/rest-w-nextjs/blob/main/src/assets/lib/user/file/upload.ts