nikita aggarwal
nikita aggarwal

Reputation: 3

Cannot read property 'file' of null in upload

I'm a beginner trying to learn Nodejs and I'm trying upload a file using express.

This is my js file : Express5.js

var express = require('express');
var path = require('path');
var fs = require('fs');
var app = express();
var bodyParser = require('body-parser');
var data='';

var multer  = require('multer');
app.use(express.static(path.join(__dirname,'tmp')));

app.use(bodyParser.urlencoded({extended :false}));

app.use(multer({ dest : '/tmp/' }).single('file1')); 


app.get('/express_upload.html',function(req,res){
 req.sendFile(__dirname+"/"+"express_upload.html");
});

app.post('/form_upload',function(req,res){
  console.log("Name : "+req.file.name);
  console.log("Path"+req.file.path);
  console.log("Type"+req.file.type);
  var myfile = __dirname+"/"+req.file.name;

  fs.readFile(req.file.path,function(req,resp){
     fs.writeFile(myfile,data,function(err){
        if(err){
            console.log(err);
        }else{
            response = {
                msg : "File uploaded successfully!",
                filename : req.file.name
            };
        }

        console.log(response);      
        res.end(JSON.stringify(response));
      });
  });
});

var server=app.listen(8081,function(){
     var host = server.address().address;
     var port = server.address().port;
     console.log("Example app listening at http://%s:%s", host, port)

  });

This is my html form : express_upload.html

<html>
<head>
    <title>Index</title>
</head>
<style>
    h2, h3{
        color:Crimson;
        text-align:center;}
</style>
<body bgcolor="MistyRose">
    <h2 >Welcome</h2>
    <hr>
    <h3>Node.js </h3>
    <form action="http://127.0.0.1:8081/form_upload" method="POST" enctype="multipart/form-data">
        <input type="file" name="file1" size=50>
        <br>

        <br><br>
        <input type="submit" value="UploadFile">
    </form>
</body>

Whenever i try to upload a file it gives error Cannot read property 'file' of null.

Error :

C:\Users\nikita\Documents\NodeJspractice>node express5.js
Example app listening at http://:::8081
Name : undefined
Path\tmp\de5a6a92ec86094615cd1690e2821248
Typeundefined
C:\Users\nikita\Documents\NodeJspractice\express5.js:33
                                    filename : req.file.name
                                                   ^

TypeError: Cannot read property 'file' of null
at C:\Users\nikita\Documents\NodeJspractice\express5.js:33:21
at FSReqWrap.oncomplete (fs.js:135:15)

I have tried most of the solutions that I was able to understand still I'm unable to resolve this. Please help if you can find any error or can propose a solution. Thank you

Upvotes: 0

Views: 3967

Answers (2)

Elad
Elad

Reputation: 2377

You overwritted the req object in line 26.

The convention in Nodejs callbacks is alwayes to return an Error object as the first parameter if an error occur, or, pass a null as the first parameter if no error has occur.

In youe case- there was no errors- so the req paremter in line 26 gets null. and null- doesn't have a file property.


By the way- you have some more problems in your code.

In line 17: res.sendFile instead of req.sendFile.

In line 21 : req.file.originalname instead of req.file.name.

Ind in line 23 : req.file.mimetype instead of req.file.type.

Use VSCode (or any ather IDE) to help you debug the code. put a breakpoint at any step and observe what your variables contains.

Upvotes: 1

Yahya
Yahya

Reputation: 746

Try This:

var express = require('express');
var path = require('path');
var fs = require('fs');
var app = express();
var bodyParser = require('body-parser');
var data='';

var multer  = require('multer');
app.use(express.static(path.join(__dirname,'tmp')));

app.use(bodyParser.urlencoded({extended :false}));

app.use(multer({ dest : '/tmp/' }).single('file1')); 


app.get('/express_upload.html',function(req,res){
req.sendFile(__dirname+"/"+"express_upload.html");
});

app.post('/form_upload',function(req,res){
console.log("Name : "+req.file.name);
console.log("Path"+req.file.path);
console.log("Type"+req.file.type);
var myfile = __dirname+"/"+req.file.name;

fs.readFile(req.file.path,function(e,file){
    fs.writeFile(myfile,data,function(err){
        if(err){
            console.log(err);
        }else{
            response = {
                msg : "File uploaded successfully!",
                filename : req.file.originalname
            };
        }

        console.log(response);      
        res.end(JSON.stringify(response));
    });
});
});

var server=app.listen(8081,function(){
    var host = server.address().address;
    var port = server.address().port;
    console.log("Example app listening at http://%s:%s", host, port)
});

The error was because rewriting req in line 24, I just change it and correct it in line 33 too.

Upvotes: 0

Related Questions