Node JS读取表单数据。

7
我想通过multipart/form-data向Node JS应用程序发送一些属性和文件。
客户端HTML表单:
<input id="picName" name="picName" class="form-control" placeholder="PicTitle..." style="border-radius: 1%; margin: 1%" type="name">
<form id="frmUploader" enctype="multipart/form-data" action="/post/picture/" method="post">
<input id="file" type="file" name="picUploader" multiple /><br>
<input class="btn btn-md btn-success" type="submit" name="submit" id="btnSubmit" value="Upload" /><br>
</form>

客户端JS:
$('#frmUploader').submit(function () {
      var username = localStorage.getItem("userName");
      var categoryName = $( "#categoryAddPic option:selected").text();
      var picTitle = $('#picName').val();

          var picture = $('input[name="picUploader"]').get(0).files[0];
          var formData = new FormData();
          formData.append('picture', picture);
          formData.append('username', username);
          formData.append('categoryName', categoryName);
          formData.append('picTitle', picTitle);

            $.ajax({
                method: 'POST',
                url: 'http://localhost:3000/post/picture',
                data: formData,
                headers:{
                    "Authorization": "bearer " + token
                },success:function (respond) {
                    ...
            });
        }
        return false;
    });

现在我想在我的Node应用程序中保存表单的数据。如果需要知道,我正在使用multer将文件保存在服务器上。
谢谢帮助。
PS:Node版本是4.8.3
Node JS:
app.post('/post/picture',function (req, res, next) {

var picName = req.body.picName;
var username = req.body.username;
var displayPic = req.body.displayPic;
var createdAt = moment();
var updatedAt = moment();
var categoryName = req.body.categoryName;
var picIdForCat = null;

try {
    if (username) {
        upload(req, res, function (err) {
            if (err) {
                return res.end("Something went wrong!");
            }
            //return res.end("File uploaded sucessfully!.");
            picName = pictureSaveFormat;
            var pictureCont = "./pictures/" + picName + ".jpg";

            User.findOne({
                where: {username: username}
            }).then(function (user) {
                var picture = {
                    picName: picName,
                    picture: pictureCont,
                    displayPic: null,
                    createdAt: createdAt,
                    updatedAt: updatedAt,
                    UserIdUser: user.idUser
                };
                Pictures.create(picture);

                if (categoryName) {
                    Pictures.findOne({
                        where: {picName: picture.picName}
                    }).then(function (pic) {
                        picIdForCat = pic.idPic;

                        Category.findOne({
                            where: {categoryName: categoryName}
                        }).then(function (category) {
                            var catId = category.idCat;
                            var catForPic = {PictureIdPic: picIdForCat, CategoryIdCat: catId};

                            CategorieForPic.create(catForPic);
                            //res.redirect('localhost:3000/index.Admin.html');
                            res.status(200).json({message: "Picture from: " + username + " with name: " + picName + " created with " + category.categoryName + "."});
                        })
                    }).catch(function (req, res, err) {
                        res.status(500).json({message: "Error: Adding Category to pic", reason: err});
                    });
                } else {
                    //res.redirect('localhost:3000/index.Admin.html');
                    res.status(200).json({message: "Picture from: " + username + " with name: " + picName + " created without a category."});
                }
            }).catch(next);
        });
    } else {
        res.status(404).json({message: "Not found.", reason: "A required parameter is missing."});
    }
}catch (err){
    res.status(500).json({message: "Fatal Server error: ", reason: err});
}
});

你能否也发布Node.js代码? - null
2
@null我尝试了使用body-parser,但是没有成功。 - pac
2个回答

3
当使用FormData对象与jQuery.ajax一起使用时,您需要将processData设置为false,以便jQuery不会尝试编码FormData对象,并将contentType设置为false,以便jQuery不会设置任何内容类型标头。当使用ajax提交FormData时,适当的内容类型标头将由jQuery自动生成。
     $.ajax({
            method: 'POST',
            url: 'http://localhost:3000/post/picture',
            data: formData,
            processData: false,
            contentType: false,
            headers:{
                "Authorization": "bearer " + token
            },
            success:function (respond) {
                ...
            });
    }

1
谢谢,我可以使用req.body在Node中正常处理该请求吗? - pac
2
你必须使用multer来处理它。 - Musa
此外,您在使用FormData对象时所使用的名称必须与服务器端完全匹配。 - Musa

0

请求头: { "Content-Type": "multipart/form-data", "Authorization": "bearer " + token }, 在我的端上是可以工作的


1
请添加一些文本来描述这个回答如何解决问题。 - haldo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接