Node.js TypeError:无法读取未定义的属性“路径" [英] Node.js TypeError: Cannot read property 'path' of undefined
问题描述
对于相同的问题,我已经找到了很多答案,但是我还没有找到可行的解决方案.我正在尝试制作一个可以使用express和multer上传文件的Web应用程序,但是我遇到的问题是没有文件正在上传,而req.file始终未定义.
I've looked at a lot of answer for this same question, but I haven't found a working solution yet. I am trying to make a web app that you can upload files to using express and multer, and I am having a problem that no files are being uploaded and req.file is always undefined.
Express和multer版本为:
"express": "^4.15.4",
"multer": "^1.3.0"
Express and multer version as:
"express": "^4.15.4",
"multer": "^1.3.0"
我的configure.js看起来像这样:
My configure.js looks this:
multer = require('multer');
module.exports = function(app) {
app.use(morgan('dev'));
app.use(multer({
dest: path.join(__dirname, 'public/upload/temp')}).single('file'));
routes(app);
app.use('/public/', express.static(path.join(__dirname, '../public')));
消费代码如下:
var tempPath = req.file.path,
ext = path.extname(req.file.name).toLowerCase(),
targetPath = path.resolve('./public/upload/' + imgUrl + ext);
if (ext === '.png' || ext === '.jpg' || ext === '.jpeg' || ext === '.gif') {
fs.rename(tempPath, targetPath, function(err) {
if (err) throw err;
res.redirect('/images/' + imgUrl);
});
} else {
fs.unlink(tempPath, function() {
if (err) throw err;
res.json(500, {error: 'Only image files are allowed.'});
});
}
表单如下:
<form method="post" action="/images" enctype="multipart/form-
data">
<div class="panel-body form-horizontal">
<div class="form-group col-md-12">
<label class="col-sm-2 control-label"
for="file">Browse:</label>
<div class="col-md-10">
<input class="form-control" type="file"
name="file" id="file">
</div>
</div>
推荐答案
我遇到了同样的问题.但是之后,我将multer版本改回了0.1.8
.一切正常.您可能需要更改package.json
文件:
"multer": "^0.1.8"
I have encountered the same problem. But then I change the multer version back to 0.1.8
. Everything works fine. You may need to alter the package.json
file:
"multer": "^0.1.8"
这篇关于Node.js TypeError:无法读取未定义的属性“路径"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!