为什么图像没有上传到node.js?

时间:2016-02-03 07:07:33

标签: node.js express file-upload multer

我正在学习node.js并尝试使用express和multer制作一个简单的图片上传应用程序来上传单个图像,重命名并保存。

以下是相关部分:

app.use(multer({dest:'/home/pc/node-dev/mypapp/public/upload/temp'}).single('file'));

表格:

<form method="post" action="/images" enctype="multipart/form-data">

            <input class="form-control" type="file" name="file">

                <textarea class="form-control" name="description" rows="2"></textarea>

                <button type="submit" id="login-btn" class="btn btn-success" type="button">Upload Image</button>

</form>

in images.js我有::

 create: function(req, res) {
            var saveImage = function() {
                console.log('saving image');
                console.log(req.body);
                console.log(req.file.path);
                var possible = 'abcdefghijklmnopqrstuvwxyz0123456789',
                    imgUrl = '';

                for(var i=0; i < 6; i+=1) {
                    imgUrl += possible.charAt(Math.floor(Math.random() * possible.length));
                }

                var tempPath = req.file.path,
                    ext = path.extname(req.file.name).toLowerCase(),
                    targetPath = path.resolve('/home/pc/node-dev/myapp/public/upload/' + imgUrl + ext);
                    console.log('imgUrl is %s', imgUrl );
                    console.log('targetPath is %s', targetPath );
                    console.log('filename is %s', req.file.name );
                    console.log('ext is %s', 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(req.file.path, function () {
                        console.log(req.file.path);

                        res.json(500, {error: 'Only image files are allowed.'});
                    });
                }
            };

我在控制台中获得的结果:

saving image
{ title: 'ddd', description: 'adwefw' }
/home/pc/node-dev/myapp/public/upload/temp/5b43a0abf25d9b05cf902d64b051a307
imgUrl is 6dnfws
targetPath is /home/pc/node-dev/myapp/public/upload/6dnfws
filename is undefined
ext is 

并在浏览器中呈现此页面:

{"error":"Only image files are allowed."}

所以一方面有一个req.file.path,另一方面,显然没有req.file.name

我对此非常困惑,所以感谢你的提示。

1 个答案:

答案 0 :(得分:1)

您需要originalname(用户计算机上文件的名称):

ext = path.extname(req.file.originalname).toLowerCase()

https://github.com/expressjs/multer#file-information