我尝试使用express.js和multer将文件上传到服务器。我无法让它工作,即使使用非常简单的代码,它仍然会出现相同的错误:
" TypeError:无法读取属性' name'未定义"
我怀疑我犯了一些非常愚蠢的错误,但我无法找出问题所在。非常感谢你的帮助!
index.html:
<!doctype html>
<html>
<head>
<title>File upload test</title>
</head>
<body>
<form id="uploadform" method="post" action="/upload" enctype="multipart/form-data">
<p><input type="file" name="img"></p>
<p><input id="submit_upload" type="submit" value="Submit"></p>
</form>
</body>
</html>
并在服务器端(server.js)
var express = require('express');
var app = express();
var multer = require('multer');
var upload = multer({ dest: 'uploads/' })
app.get('/', function(req, res){
res.sendfile(__dirname + '/client/index.html');
});
app.post('/upload', upload.single('img'), function (req, res) {
//var form_description = req.body.description;
console.log(req.files.name);
// insert operations into database get placed here
res.redirect('/');
});
package.json:
{
"name": "upload-example",
"version": "0.0.0",
"description": "A file upload example",
"main": "server.js",
"repository": "",
"author": "",
"dependencies": {
"async": "~0.2.8",
"express": "^3.2.6",
"multer": "^1.1.0",
"socket.io": "~0.9.14"
}
}
答案 0 :(得分:0)
1)您configure悼念接受单个文件,单个文件将存储在req.file
中。
2)原始文件名存储在req.file.originalname
。
3)临时文件名存储在req.file.filename
。