我正在尝试学习使用以下代码上传文件:
var express = require('express');
var app = express();
var fs = require("fs");
var bodyParser = require('body-parser');
var multer = require('multer');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(multer({dest:'./uploads/'}).single('file'));
app.get('/index.htm', function (req, res) {
res.sendFile( __dirname + "/" + "index.htm" );
})
app.post('/file_upload', function (req, res) {
console.log(req.file.name);
console.log(req.file.path);
console.log(req.file.type);
var file = __dirname + "/" + req.file.name;
console.log("File Name: " file);
fs.readFile( req.file.path, function (err, data) {
fs.writeFile(file, data, function (err) {
if( err ) {
console.log( err );
} else {
response = {
message:'File uploaded successfully',
filename:req.file.name
};
}
console.log( response );
res.end( JSON.stringify( response ) );
});
});
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
文件已成功上传到/ uploads目录中,但是,我无法从那里打开文件。另外,当我尝试console.log(req.file.name);
得到不确定的输出时,我无法打印文件名。
任何帮助将不胜感激。提前致谢。
编辑:按要求输出控制台
Info: Start process (2:45:28 PM)
Example app listening at http://:::8081
undefined
uploads\3cbe4d0c18a778a9faddc6243c26b26a
undefined
File Name: undefined
{ message: 'File uploaded successfully', filename: undefined }
Process canceled
Info: End process (2:52:29 PM)