Search code examples
multipartform-datanext.jscorruptformidable

Corrupt image when uploading to Next.js API


I'm trying to upload an image as form-data to a Nextjs api route. I use the package formidable to parse and save the file in a server folder. For the http request I use postman on the client.

Here ist the backend code:

import formidable from 'formidable';

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

export default async (req, res) => {
  const form = new formidable.IncomingForm();

  form.on('fileBegin', (name, file) => {
    file.path = "./" + file.name

  });

  form.parse(req, (err, fields, files) => {
    console.log( files);
  });

  res.statusCode = 200
  res.end()
};

The image (jpeg) is saved in the folder. However, it appears to be corrupt or damaged. Here is the original image:

source image

corrupt image


Solution

  • Next.js need the package formidable-serverless instead of formidable

    https://github.com/node-formidable/formidable/issues/629