Danish Butt
Danish Butt

Reputation: 1

TypeError [ERR_INVALID_ARG_TYPE]: The "oldPath" argument must be of type string or an instance of Buffer or URL. Received undefined. Encoutring error

Getting error on filepath and originalFilename..

I started learning MERN from scratch and encountring with these error mentioned below, I tried to resolve it,but not avail.
when i run this file getting this error on the line no 16.
TypeError [ERR_INVALID_ARG_TYPE]: The "oldPath" argument must be of type string or an instance of Buffer or URL. Received undefined

FileUploading.js file code is .

// Node.js server code
const formidable = require("formidable");
const fs = require("fs");
const http = require("http");

http.createServer((req, res) => {
  if (req.url == "/fileupload" && req.method.toLowerCase() === 'post') {
    const form = new formidable.IncomingForm();
    form.parse(req, (err, fields, files) => {
      if (err) {
        res.writeHead(400, { "Content-Type": "text/plain" });
        res.write("An error occurred during file upload");
        res.end();
        return;
      }
      const oldPath = files.filetoupload.filepath; // Use 'filepath' instead of 'path'
      const newPath = "/home/danish-butt/Documents/uploadedByNodeJs/" + files.filetoupload.originalFilename;
      fs.rename(oldPath, newPath, (err) => {
        if (err) {
          res.writeHead(500, { "Content-Type": "text/plain" });
          res.write("File upload failed");
          res.end();
          return;
        }
        res.writeHead(200, { "Content-Type": "text/html" });
        res.write("File uploaded and moved!");
        res.end();
      });
    });
  } else {
    fs.readFile("fileForm.html", (err, data) => {
      if (err) {
        res.writeHead(500, { "Content-Type": "text/plain" });
        res.write("Error loading form");
        res.end();
        return;
      }
      res.writeHead(200, { "Content-Type": "text/html" });
      res.write(data);
      res.end();
    });
  }
}).listen(8080, () => {
  console.log("Server listening on http://localhost:8080/");
});

and in addition encountring on line no 17 filetoupload.originalFilename.

There is a file fileForm.html from where the form getting read by fs .

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

Help me to find these errors. Thanks for helping me..

Upvotes: 0

Views: 13

Answers (0)

Related Questions