【问题标题】:TypeError: Cannot read property 'image' of undefinedTypeError:无法读取未定义的属性“图像”
【发布时间】:2014-10-20 07:23:26
【问题描述】:

我的源代码有问题,但我不知道是什么问题 - 请帮忙。我一直在寻找一些解决方案,找到了一些并根据它们更新了源代码,但没有帮助。

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);

【问题讨论】:

  • 尝试req.body.files 而不是req.files。如果您从 HTTP 请求发送一些数据,它将存储在请求正文中。 stackoverflow.com/questions/11625519/…
  • 同样的问题 - 当我把控制台 req.body 它是空的。请注意,它是多部分而不是 json。

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


【解决方案1】:

body-parser 中间件不处理 multipart 主体。

来自body-parsergithub:

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

【讨论】:

    猜你喜欢
    • 2021-12-10
    • 1970-01-01
    • 2021-02-19
    • 2021-10-04
    • 1970-01-01
    • 2022-01-14
    • 2019-06-08
    • 2019-03-02
    • 2020-04-20
    相关资源
    最近更新 更多