在multer中上传文件之前如何获取身体? [英] How to get the body before uploading file in multer?

查看:32
本文介绍了在multer中上传文件之前如何获取身体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,管理员可以上传MP3文件并向其提交参数(例如歌曲名称).

In my project the admins have the ability to upload MP3 files and submit parameters to it like song name.

我决定使用 multer中间件来处理 multipart/form-data

我的问题是 req.body.gender 返回始终未定义,因为我必须在 uploadSong 侦听器中使用它.我想上传性别为零的歌曲.

My problem is req.body.gender returns always undefined, because I have to use it inside the uploadSong listener. I want to upload the song when the gender is zero.

index.ejs

<form method="post" action="/acp" role="publish" enctype="multipart/form-data">
    <div class="form-group">
        <input type="file" name="song" id="song" accept="audio/mpeg">
    </div>

    <input type="checkbox" name="gender" checked data-toggle="toggle" data-on="Male" data-off="Female">
</form>

app.js

var uploadSong = upload.single('song');
app.post('/acp', isLoggedIn, function (req, res) {

    console.log(req.body.gender); // returns "undefined"

    if(req.body.gender == 0) { // returns "undefined"

        uploadSong(req, res, function (err) {
            if (err) {
                res.send('uploaded');
                return;
            }
            res.redirect('/');

        });
    
    }
});

推荐答案

(A)multer无法使用.

(A) Not possible with multer.

(B)使用 busboy .它使用流来解析表单数据,因此您可以在上传文件和将字段用作事件之前获取表单元素的值.

(B) Use busboy. It uses streams to parse the form data and so you can get form elements values before the file upload and the fields are made available as events.

(C)另一个解决方案(如果您更喜欢使用multer)是使用multer,但添加标头以发送参数的值以在文件上传之前进行检查.请求到达服务器后,便可以使用标头.

(C) Another solution (if you prefer using multer) is to use multer but add a header to send the value of the parameter to check before file upload. Headers are available as soon as the request reaches the server.

这篇关于在multer中上传文件之前如何获取身体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆