【问题标题】:TypeError: Cannot read property 'thumbnail' of undefinedTypeError:无法读取未定义的属性“缩略图”
【发布时间】:2015-12-01 23:29:52
【问题描述】:

这是我的 server.js 文件 我正在尝试在服务器上查找上传图片。我开始知道 multipart 现在不起作用了。

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。但是在我的代码中如何以及在何处使用它呢?

【问题讨论】:

  • tmp_pathtarget_path的值是多少?
  • tmp_path 是用户提供的上传文件的路径,target_path 是最终存储的位置。
  • 我明白了,但它们是未定义的吗?这是代码中唯一可以看到可能错误的地方。除非您在前端有更多与该表单相关的代码。
  • 未定义为?它定义为:var tmp_path = req.files.thumbnail.path;
  • 如果你 console.log tmp_path 和/或 target_path 你的终端会说什么?

标签: node.js multer


【解决方案1】:

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

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

【讨论】:

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