我正在尝试使用Node.js上传照片。但是当我上传时,它会显示以下错误:
无法读取未定义的属性文件
在C:\ new \ file.js:13:26
看起来我对req.files.file.name
做错了,我不明白。可能是什么问题?
以下是代码:
file.js
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: '/files/'}).single('file'));
app.get('/index.html', function (req, res) {
res.sendFile(__dirname + '/' + '/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.name, function (err, data) {
fs.writeFile(file, data, function (err) {
if (err) {
console.log("Error reading");
} 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("The server is running at http://%s:%s ", host, port);
});
的index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="http://127.0.0.1:8081/file_upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="submit">
</form>
</form>
</body>
</html>
答案 0 :(得分:1)
这就是我的工作,工作正常:
var uploadPath = 'public/uploads/';
var upload = multer({dest: uploadPath});
router.post('/image', upload.single('thePhoto'), function (req, res) {
var uploadedFile = uploadPath + req.file.filename;
答案 1 :(得分:0)
问题可能是因为你已经在app.use()中添加了multer,它在控制转到post方法之前解析所有数据。所以我认为你应该使用fs或multer而不是两者。