1

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>

3 Answers 3

3

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

0

This is a complete working example:

upload.js

'use strict';

const fss = require('fs')
const pth = require('path');
const exp = require('express');
const swg = require('swig');
const efm = require("formidable");
const app = exp();

const thm = swg.compileFile(pth.join(__dirname, '', 'upload.html'));
app.listen(9009);
app.get(`/`, async (q, r) => r.send(thm({ msg: "Select a File to Upload" })));
app.get(`/:msg`, async (q, r) => r.send(thm({ msg: q.params.msg })));
app.post('/upload', (r, q) => {
    var form = new efm.IncomingForm();

    form.parse(r, (e, p, f) => {
        let dir = pth.join(__dirname, '', '/media/');

        if (!fss.existsSync(dir)) {
            fss.mkdirSync(dir);
        }

        let nPth = dir + f.file.name;
        try {
            fss.accessSync(nPth, fss.F_OK);
            q.redirect("/File Exists");
        } catch (file_e) {
            let err = fss.renameSync(f.file.path, nPth);
            q.redirect(err ? "/Error" : "/File Uploaded");
        }
    });
});
  1. You can use fss.access for "A-SYNC" operation.
  2. Its better to use "A-SYNC" functions.

upload.html

<h3>{{msg}}</h3>
<br/>
<form action="upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit">
</form>
1
0

fileupload object doesn't exist within file, hence you are getting the undefined error.

To access the old path use :

var oldpath = files.upload.filepath;

Not the answer you're looking for? Browse other questions tagged or ask your own question.