如何从请求主体(Javascript)中查看/检索FormData对象

How to view / retrieve a FormData object from request body (Javascript)

本文关键字:检索 对象 FormData 请求 主体 Javascript      更新时间:2023-09-26

你好,提前感谢

我正在编写一个视频上传器网络应用程序,可以上传视频并将其保存到mongo数据库中。我在网上搜索了几天,想知道如何将DataForm对象从请求体中取出,以便将其保存在数据库中。

我只是不确定我在服务器端要找什么。如何从请求正文中获取视频数据?这是我的代码:

//client side
upload: function(event) {
        // prevent default browser submit
        event.preventDefault();
        event.stopPropagation();
        var fileInput = this._("file1").files[0];
        if (!fileInput) {
            return;
        }
        var formdata = new FormData();
        formdata.append("file1", fileInput);
        api.addContent(formdata, this.updateCB);
}
//api call
addContent: function(data, cb) {
        var url = "/api/content";
        $.ajax({
            url: url,
            data: data,
            processData: false,
            contentType: false,
            type: 'POST',
            headers: {'Authorization': localStorage.token},
            success: function(res) {
                if (cb)
                    cb(true, res);
            },
            error: function(xhr, status, err) {
                // if there is an error, remove the login token
                delete localStorage.token;
                if (cb)
                    cb(false, status);
            }
        });
}
//server side
app.post('/api/content', function (req,res) {
    user = User.verifyToken(req.headers.authorization, function(user) {
        if (user) {
        // req.body.data should work
        Content.create({data:req.body.data,user:user.id}, function(err,content) {
        if (err) {
            res.sendStatus(403);
            return;
        }
        res.json({content:'content saved'});
        });
        } else {
            res.sendStatus(403);
        }
    });
});

下面是chrome中请求主体的屏幕截图:请求正文

原来我需要解析formdata对象。

var multiparty = require('multiparty');

    app.post('/api/content', function (req,res) {
        console.log(req);
        // validate the supplied token
        user = User.verifyToken(req.headers.authorization, function(user) {
            if (user) {
            var form = new multiparty.Form();
            form.parse(req, function(err, fields, files) {
            var video_path = String(files.file1[0].path);
            Content.create({video:video_path,user:user.id}, function(err,content) {
            if (err) {
                res.sendStatus(403);
                return;
            }
            res.json({content:content});
            });
            });
            } else {
                res.sendStatus(403);
            }
        });
    });