0

I am trying to just do a simple file upload with formidable in node js, and with this code: `

app.post("/upld", function(req, res){
  var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
      var oldpath = files.filetoupload.filepath;
      var newpath = 'uploads/' + files.filetoupload.newFilename;
      fs.rename(__dirname + oldpath, __dirname + "/" + newpath, function (err) {
        if (err) throw err;
        res.write('File uploaded');
        res.end();
      });
});
});

and here is the html form:

  <body>
    <form action="upld" method="post" enctype="multipart/form-data">
      <input type="file" name="filetoupload"><br>
      <input type="submit">
    </form>
   </body>
</html>

I get an error saying that there is no file or directory named "tmp/9885a1a737766e7a6963b6a00" I know that that temp folder will change everytime, that is just the most recent attempted one.

I have tried looking at the file data by sending it through the response, but all of the information there checks out. How can I access the uploaded file from its temp folder?

1 Answers1

0

Try this, for the oldpath, do not add the __dirname, just use the oldpath:

const express = require('express');
const formidable = require('formidable');
const fs = require('fs');

const app = express();

app.get('/', (req, res) => {
    res.send(`
    <form action="upld" method="post" enctype="multipart/form-data">
        <input type="file" name="filetoupload"><br>
        <input type="submit">
    </form>
  `);
});

app.post("/upld", function (req, res) {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
        var oldpath = files.filetoupload.filepath;
        var newpath = 'uploads/' + files.filetoupload.newFilename;
        fs.rename(oldpath, __dirname + "/" + newpath, function (err) { // <<======= ONLY oldpath DO NOT ADD __dir
            if (err) throw err;
            res.write('File uploaded');
            res.end();
        });
    });
});

app.listen(3000, () => {
    console.log('Server listening on http://localhost:3000 ...');
});
Paulo Fernando
  • 3,148
  • 3
  • 5
  • 21
  • So that fixed the error I was having, so I am pretty sure it is targeting the correct folders now, but, now it says that "EXDEV: cross-device link is not permitted." – Mason Walker Dec 14 '22 at 14:17
  • Maybe try this? https://stackoverflow.com/questions/43206198/what-does-the-exdev-cross-device-link-not-permitted-error-mean – Paulo Fernando Dec 14 '22 at 15:16