2015-11-30 51 views
0

這是我的server.js文件 我正在嘗試在服務器上查找上傳圖片。我開始知道多部件現在不起作用。TypeError:無法讀取屬性'縮略圖' undefined

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 

如何將圖像立即上傳?我第一次使用這個。我開始知道現在使用的是裸眼。但是,在我的代碼中如何以及在哪裏使用它?

+0

''''''tmp_path'''和''''target_path'''的值是什麼? –

+0

tmp_path是用戶上傳文件的路徑,target_path是最終存儲的地方。 – RayOfHope

+0

我明白了,但他們沒有定義?這是代碼中唯一可以看到可能的錯誤的地方。除非你在前端使用了更多的代碼。 –

回答

0

您正在使用的正文解析器中間件不支持多部分(文件上傳)。它只支持JSON或URL編碼的表單提交。我要指出你的方向this stack overflow question。它談到你遇到的同樣的問題。

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

相關問題