TypeError:无法读取属性' image'未定义的

时间:2014-08-26 20:40:42

标签: node.js image file-upload express multipartform-data

我的源代码有问题,但我无法弄清楚 - 请帮忙。我正在寻找一些解决方案,根据它们找到一些和更新的源代码,但没有帮助。

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 个答案:

答案 0 :(得分:4)

body-parser中间件无法处理multipart个主体。

来自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