htmlnode.jsexpressformidable

node.js formidable with express.js


I am new to node.js and learning it from various sources such as bootcamps, websites, etc. I want to upload a file using formidable module in node.js and express.js framework. Everytime I run this code it show an error....

  var oldpath = file.fileupload.path;
                                   ^
  TypeError: Cannot read property 'path' of undefined

I have used body parser to receive the name of the file.

Node.js code:

var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var formidable = require("formidable");
var fs = require("fs");
var PORT = process.env.PORT || 5000

app.set("view engine","ejs");
app.use(bodyParser.urlencoded({extended: true}));

app.get("/" , function(req, res){
	res.render("form");
});
app.post("/fileupload" , function(req, res){
	var fileupload = req.body.filetoupload;
    var form =  new formidable.IncomingForm();
    form.parse(req, function(err, fields, files){
    	 var oldpath = files.fileupload.path;
         var newpath = "C:/Users/ayush/"+files.fileupload.name;
         fs.rename(oldpath, newpath, function(err){
         	if(err)
         		console.log(err);
         	else{
                res.write("File Uploaded");
                res.end();
            }
         }); 
    });
});

app.listen(PORT, function(){
	console.log("Server started");
});
<!DOCTYPE html>
<html>
<head>
	<title>FileUpload</title>
</head>
<body>
	<form action="/fileupload" method="POST">
        <label>
        	File: 
     		<input type="file" name="filetoupload" enctype="multipart/form-data">
        </label>
		<button>Submit</button>
	</form>

</body>
</html>


Solution

  • I'm new at this too but the form enctype in form.ejs should be in the <form> tag. Instead of:

    <form action="/fileupload" method="POST">
    

    try:

    <form action="/fileupload" method="POST" enctype="multipart/form-data">
    

    You should now have your files object.

    Cheers,

    Mark