Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node JS read Form Data

I want to send some attributes and a file to a Node JS application with multipart/form-data.

Client HTML Form:

<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>

Client 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;
    });

Now I want to save the data of the form in my Node application. If it is necessary to know too, I´m using multer for saving the file on the server.

Thanks for help.

PS: The node version is 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});
}
});
like image 454
pac Avatar asked Apr 10 '18 22:04

pac


People also ask

How do I get node js form data?

To get started with forms, we will first install the body-parser(for parsing JSON and url-encoded data) and multer(for parsing multipart/form data) middleware. var express = require('express'); var bodyParser = require('body-parser'); var multer = require('multer'); var upload = multer(); var app = express(); app.

How do I get data from node JS to HTML?

If your node server also serves this HTML page, then you can use a relative path to point to your route like this: action="/handle-form-data" . The input tag nested inside the form is used to collect user input. You have to assign a name property to your data so that you can recognize this piece of data on the server.


1 Answers

When using a FormData object with jQuery.ajax, you have to set processData to false so that jQuery will not try to encode the FormData object and contentType to false so that jQuery will not set any content type headers. When FormData is used with ajax the proper content type header is generated for you.

     $.ajax({
            method: 'POST',
            url: 'http://localhost:3000/post/picture',
            data: formData,
            processData: false,
            contentType: false,
            headers:{
                "Authorization": "bearer " + token
            },
            success:function (respond) {
                ...
            });
    }
like image 182
Musa Avatar answered Oct 18 '22 09:10

Musa