我正在学习节点js&在教程点表达js在那个课程我尝试上传文件,但每当我尝试它显示错误为“无法读取未定义的属性'文件'请帮助我解决这个问题。
var express = require('express');
var app = express();
var fs = require("fs");
var bodyParser = require('body-parser');
var multer = require('multer');
var upload=multer({ dest: '/tmp/'});
// app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/test', function (req, res) {
res.sendFile( __dirname + "/" + "/public/index.html" );
})
app.post('/file_upload', function (req, res) {
console.log(req.files.file.name);
console.log(req.files.file.path);
console.log(req.files.file.type);
var file = __dirname + "/" + req.files.file.name;
fs.readFile( req.files.file.path, function (err, data) {
fs.writeFile(file, data, function (err) {
if( err ){
console.log( err );
}else{
response = {
message:'File uploaded successfully',
filename:req.files.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)
})
答案 0 :(得分:0)
您的代码有多个问题:
var upload
)来处理文件上传res
我已纠正这些问题并立即上传。
同时检查:
tmp
enctype="multipart/form-data"
<input type="file" name="myfile">
) var express = require('express');
var app = express();
var fs = require("fs");
var path = require("path")
var bodyParser = require('body-parser');
var multer = require('multer');
var upload = multer({dest: 'tmp/'});
// app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended: false}));
app.get('/test', function (req, res) {
res.sendFile(__dirname + "/" + "/public/index.html");
})
app.post('/file_upload', upload.single("myfile"), function (req, res, next) {
console.error(">>>", req.file)
console.log(req.file.originalname);
console.log(req.file.path);
console.log(req.file.mimetype);
var file = __dirname + "/" + req.file.originalname;
fs.readFile(req.file.path, function (err, data) {
fs.writeFile(file, data, function (err) {
if (err) {
console.log(err);
} else {
var response = {
message: 'File uploaded successfully',
filename: req.file.originalname
};
}
console.log(response);
res.json(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)
})
<form action="/file_upload" method="post" enctype="multipart/form-data">
<input type="file" name="myfile">
<button type="submit">senden</button>
</form>