req.file 未定义(multer,node.js)

req.file is undefined (multer, node.js)

我尝试上传图片已有一段时间了,但 req.file 仍未定义。有人能看出原因吗?

this is my page. I am able to pick an image when I click the '+' glyphicon, but on the server side req.file is still empty.

EJS文件

input[type="file"] 和 input[type="submit"] 有 css 样式 display: none

<form action="/profile/addProfilepicture" method="post" id="form" enctype="multipart/form-data">
            <span id="upload" class="glyphicon glyphicon-plus-sign"></span>
            <label for="profilePic"></label>
            <input id=profilePic type='file'  />
            <input type="submit">
        </form>

        <img class="profileImg"
             src="<%="images/pexels-photo-370799.jpeg"%>"
             alt="fail">

客户端JS文件

当我点击“+”字形图标时,它会让我选择一张图片。当我这样做时,这将触发表单提交并发送 post 请求。

   $("#upload").on('click',function() {
        $("input[type='file']").click();
    });

    $('input[type="file"]').change(function (e) {
       $("input[type='submit']").click()
    });

服务器端 JS

在服务器端它停在:

TypeError: Cannot read property 'filename' of undefined at C:\Users\Tijl Declerck\Desktop\projects\digitalNomadApp\routes\profile.js:27:38 at Immediate._onImmediate (C:\Users\Tijl Declerck\Desktop\projects\digitalNomadApp\node_modules\multer\lib\make-middleware.js:53:37) at runCallback (timers.js:793:20) at tryOnImmediate (timers.js:751:5) at processImmediate [as _immediateCallback] (timers.js:722:5)

我试过的 console.logs 给了我这个:req.body returns 一个空对象和 req.file returns 未定义。

var express = require('express');
var router = express.Router();
var multer  = require('multer');
var User = require('../models/Users');

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './public/uploads/profilePics')
    },
    filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now())
    }
});

var upload = multer({ storage: storage }).single('myImage');


router.post('/addProfilePicture', function (req, res) {

    var profilePicUrl = '';
    upload(req, res, function (err) {
        if (err) {
            // An error occurred when uploading

        } else {
            console.log(req.file);
            profilePicUrl = req.file.filename;

            User.update({username: req.user.username}, {'profilePic.uploaded': true, 'profilePic.link': profilePicUrl}, function(err, doc){
            console.log('THIS IS DONE')
            });
        }
    });
});

您必须为您的文件输入提供一个名称,它应该与单个方法的名称相匹配,这来自 multer 文档:

.single(fieldname)

Accept a single file with the name fieldname. The single file will be stored in req.file.

这没有很好的记录,但字段名是指输入名称属性

EJS文件

<input id='profilePic' name='myImage' type='file'  />

快递

...
var upload = multer({ storage: storage }).single('myImage');
...