Skip to content

node / formidable - problem with documentation - how to save files to dir? #861

Answered by nagayev
robokonk asked this question in Q&A
Discussion options

You must be logged in to vote

You can use code like this (code from my NextJS app):

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

const saveFile = async (file) => {
  const data = fs.readFileSync(file.filepath);
  fs.writeFileSync(`./public/${file.originalFilename}`, data);
  await fs.unlinkSync(file.filepath); 
  return;
};

Replies: 3 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@wbt
Comment options

wbt Dec 9, 2022
Collaborator

Answer selected by nagayev
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
4 participants