node-formidable / formidable

The most used, flexible, fast and streaming parser for multipart form data. Supports uploading to serverless environments, AWS S3, Azure, GCP or the filesystem. Used in production.
MIT License
7k stars 680 forks source link

TypeError: String(file) on version 2.x #889

Closed nagayev closed 1 year ago

nagayev commented 1 year ago

Support plan

Context

What are you trying to achieve or the steps to reproduce?

You can use this code.

import formidable from "formidable";
import fs from "fs";

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

const post = async (req, res) => {
  console.log('handling file...');
  const form = new formidable.IncomingForm();
  form.parse(req, async function (err, fields, files) {
    if (err) console.error(err);
    console.log(files.file.newFilename);
    try{
      await saveFile1(files.file);
    }
    catch(e){
      console.log('Error was catched: ',e);
    }
    return res.status(201).send("Nothing");
  });
};

const saveFile1 = async (file) => {
  console.log(file); //**TypeError**
  const data = fs.readFileSync(file.filepath);
  fs.writeFileSync(`./public/${file.originalFilename}`, data);
  //await fs.unlinkSync(file.path);
  return;
};

export default (req, res) => {
  req.method === "POST"
    ? post(req, res)
    : req.method === "PUT"
    ? console.log("PUT")
    : req.method === "DELETE"
    ? console.log("DELETE")
    : req.method === "GET"
    ? console.log("GET")
    : res.status(404).send("");
};

What was the result you got?

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

What result did you expect?

Working app.

nagayev commented 1 year ago

Workaround: Apply patch from my PR #890