TypeError: Cannot read property 'image' of

2019-02-19 19:03发布

There is something wrong in my source code but I'm not able to figure out what - please help. I was looking for some solutions found some and updated source code according them but didn't help.

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

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

var form = "<!DOCTYPE HTML><html><body>" +
"<form method='post' action='/upload' enctype='multipart/form-data'>" +
"<input type='file' name='image' id='image'/>" +
"<input type='submit' /></form>" +
"</body></html>";



app.get('/', function(req, res){
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(form);

});

app.post('/upload', function(req, res){
    fs.readFile(req.files.image.path, function(err, data){

        var imageName = req.files.image.name
        if(!imageName){
            console.log("There was an error");
            res.redirect('/');
            res.end();
        }else{
            var newPath = __dirname + "/uploads/fullsize/" + imageName;

            fs.writeFile(newPath, data, function(err){
                res.redirect("/uploads/fullsize/" + imageName);
            });
        }

    });
});

app.listen(8080);

1条回答
再贱就再见
2楼-- · 2019-02-19 19:48

The body-parser middleware does not handle multipart bodies.

From the body-parser github:

This does not handle multipart bodies, due to their complex and typically large
nature. For multipart bodies, you may be interested in the following modules:

https://github.com/expressjs/body-parser

查看更多
登录 后发表回答