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

时间:2015-11-30 22:04:51

标签: node.js multer

这是我的server.js文件 我想在服务器上找到上传图片。我开始知道多部分现在还不起作用。

var config=require('./config');
var mongoose=require('mongoose');
var bodyparser=require('body-parser');
var express = require('express');
var morgan=require('morgan');
var nodemailer=require('nodemailer');
var fs=require('fs');
var FB=require('fb');
var app = express();
app.use(bodyparser.urlencoded({extended:true}));
//app.use(express.bodyparser({uploadDir:'./uploads'})); //This is showing error.
app.use(bodyparser.json());
app.use(morgan('dev'));

app.use('/public',express.static(__dirname + '/public'));


mongoose.connect(config.database,function(err){
    if(err)
        console.log(err);
    else
        console.log('database connected');
});

app.listen(config.port,function(err){
    if(err)
        console.log(err);
    else
        console.log('server running at  '+config.port);

});

app.get('/',function(req,res){
    res.sendFile(__dirname +'/public/app/views/index.html' );
});
app.post('/file-upload', function(req, res) {
    // get the temporary location of the file
    var tmp_path = req.files.thumbnail.path;
    // set where the file should actually exists - in this case it is in the "images" directory
    var target_path = './public/images/' + req.files.thumbnail.name;
    // move the file from the temporary location to the intended location
    fs.rename(tmp_path, target_path, function(err) {
        if (err) throw err;
        // delete the temporary file, so that the explicitly set temporary upload dir does not get filled with unwanted files
        fs.unlink(tmp_path, function() {
            if (err) throw err;
            res.send('File uploaded to: ' + target_path + ' - ' + req.files.thumbnail.size + ' bytes');
        });
    });
});

这是我的表格:

<form method="post" enctype="multipart/form-data" action="/file-upload">
    <input type="text" name="username">
    <input type="password" name="password">
    <input type="file" name="thumbnail">
    <input type="submit">
</form>

显示以下错误:

TypeError: Cannot read property &#39;thumbnail&#39; of undefined

如何上传图片?我是第一次使用它。我开始知道multer现在用了。但是在我的代码中如何以及在何处使用它?

1 个答案:

答案 0 :(得分:0)

您正在使用的正文解析器中间件不支持multipart(文件上传)。它仅支持JSON或url编码的表单提交。我将指向this stack overflow question的方向。它谈到了你遇到的同样问题。

解决方案:您需要支持多部分提交的不同中间件。