【问题标题】:Node.js image uploadNode.js 图片上传
【发布时间】:2020-12-14 19:24:31
【问题描述】:

我正在使用 Multer 上传图像。图片上传就好了。但主要问题是我无法从req.body 检索其他输入文本字段数据。我的req.body{}

HTML 代码

<form action="/postRoute" method="POST" enctype="multipart/form-data">
    <div class="form-group row">
        <div class="col-sm-6 mb-3 mb-sm-0">
            <input type="text" placeholder="Title" name="title">
        </div>
        <div class="col-sm-6">
            <input type="text" placeholder="Description" name="description">
        </div>
    </div>
    <div class="file-field input-field">
        <div class="btn grey">
            <span>Image</span>
            <input type="file" name="image" multiple>
        </div>
    </div>
    <button type="submit" class="btn btn-primary btn-user btn-block">
        List
    </button>
</form>

路线代码

router.post('/postRoute', (req, res) => {
    console.log(req.body);

    upload(req, res, (err) => {
        if(err) {
         throw err;   
        } else {
            console.log('logging files');
            console.log(req.files);

            if(req.files.length <= 0) {
                res.render('listing', {
                    msg: 'Error: No File Selected!'
                })
            } else {
                let list = Listing();
                list.title = title;
                list.description = description;
                list.photos = req.files[0].filename
                
                list.save((err) => {
                    if(err) throw err;
            
                    req.flash('success', 'Product Listed Successfully!')
                    res.redirect('/')
                })
            }
        }
    })
})

MULTER 代码

//Set Storage Engine
const storage = multer.diskStorage({
    destination: './public/uploads/',
    filename: function(req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
    }
})

//Init Upload
const upload = multer({
    storage: storage,
    llmits: {fileSize: 1000000},
    fileFilter: (req, file, cb) => {
        checkFileType(file, cb);
    }
}).array('image')

//Check File Type
function checkFileType (file, cb) {
    //Allowed ext
    const fileType = /jpeg|jpg|png|gif/;

    //Check ext
    const extname = fileType.test(path.extname(file.originalname).toLowerCase());

    //Check Mime
    const mimetype = fileType.test(file.mimetype)

    if(mimetype && extname) {
        return cb(null, true);
    } else {
        cb('Error: Images Only!');
    }
}

当我从表单中删除 enctype="multipart/form-data" 时,我会收到带有数据的 req.body,但是,我的图像不会出现。

【问题讨论】:

标签: html node.js multer


【解决方案1】:

你需要使用multer作为中间件:

router.post('/postRoute', upload, (req, res) => {
    console.log(req.body);
 // other code
}

documentation

【讨论】:

  • 所以你的意思是我在路由中调用的上传函数应该在我的中间件区域?
  • @UmairNadeem 是的
猜你喜欢
  • 2022-01-15
  • 2015-01-12
  • 1970-01-01
  • 1970-01-01
  • 2018-01-14
  • 1970-01-01
  • 1970-01-01
  • 2011-07-06
  • 2014-10-01
相关资源
最近更新 更多