skip to Main Content

I want to upload a file using formidable and then change it’s directory. In the tutorial, the code is this

var http = require("http");
var fs = require("fs");
var formidable = require("formidable");

http.createServer(function (req, res) {
    if (req.url == "/fileupload") {
        var form = new formidable.IncomingForm();
        form.parse(req, function (err, fields, files) {
            var oldpath = files.filetoupload.path;
            var newpath = "C:/Users/devsi/" + files.filetoupload.originalFilename;
            fs.replace(oldpath, newpath, function (err) {
                if (err) throw err;
                res.write("File uploaded and moved!");
                res.end();
            });
        });
    } else {
          res.writeHead(200, { "Content-Type": "text/html" });
          res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
          res.write('<input type="file" name="fileupload"><br>');
          res.write('<input type="submit">');
          res.write("</form>");
          return res.end();
    }
}).listen(8080);

But this gives the above mentioned error. What’s wrong?

I tried changing the fields and files arguments thinking it would solve it but the output was still the same. The file name is app.txt (few kbs) so it shouldn’t be a problem.

2

Answers


  1. You should use
    fs.rename()
    in place of fs.replace() since fc.replace() doesn’t exist actually.

    See https://nodejs.org/api/fs.html

    Login or Signup to reply.
  2. There is no replace method for fs. You can use the rename method to move the uploaded file to a new directory.

    fs.rename(oldpath, newpath, function (err)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search