Suleman Mirza Suleman Mirza - 1 year ago 64
Node.js Question

how to parse multipart/form-data sent through ajax request.?

I am trying to parse a multipart/form-data sent from

and on the server side data is coming in
not in
as stated in the documentation of express.

What I am trying to do is sending multiple image files and form data through
,then receive it on the server side and sent those images as an attachments through nodemailer, so to sent it through nodemailer I need to be able to read that, what I get is just garbage of data in req.body, which I cannot even read. The code is below.

Client-Side Ajax request sending function:-

$('.contact-button').on('click', function(e) {
var data = new FormData();

var filesList = document.getElementById('files');
for (var i = 0; i< filesList.files.length; i ++) {
data.append('file', filesList.files[i]);

data.append('messageData', $('#contact-form').serialize());

url: '/api/contactus/',
data: data,
processData: false,
type: "POST",
contentType: 'multipart/form-data',
mimeType: 'multipart/form-data',
success: function (data) {

console.log("SUCCESS IN AJAX");
error: function (err) {
console.log('error in AJAX');

Server Side API handling the Request:-

function contactUs (req, res, next) {

console.log("TESTING Body ");

console.log("TESTING Files");

var Transport = email.createTransport("SMTP", {
service: "Gmail",
auth: {
user: "",
pass: "dumy1234"

host : "",
port : "587",
domain : "",
to : "",
from : "",

subject : "[Technical Support] "+EmailInfo.Name + " Submitted an Issue!",
reply_to: req.body.Email,
html : "<h2 >Message Details</h2>",
authentication : "login",
username: '',
password: 'dumy1234'
}, function (err, result) {
if (err) {
next('email sending failed', err);
} else {
res.json('email sending Success');

So the two questions is how to parse multipart data coming through ajax request.?
second How to sent multipart data as an attachment through nodemailer.?

Just keep in mind I already tried to use
, but when I inserted it in my app.js it gave me
400 bad request
,and didn't even executed the

Answer Source

Using contentType: false solved many problems for me , just for the people who were looking for an answer to the same question , here is working and updated code.

Client Side Js:-

    submitHandler: function (form) {
        if(isClicked) {
            $('#result').removeClass('alert-success').addClass('alert-error').html("Ticket Already submitted").show();
            return false;
        isClicked = true;
        var data = new FormData();
        data.append('messageData', $('#contact-form').serialize());
        var filesList = document.getElementById('files');
        for (var i = 0; i < filesList.files.length; i ++) {
            data.append('file', filesList.files[i]);
            url:         '/api/contactus/',
            data:        data,
            processData: false,
            type:        'POST',
            contentType: false,
            success:     function (data) {
                $('#contact-form').html('<p><span>Thank You for contacting us!</span><br> We will get back to you very soon.<br> Your Ticket No. is <strong>'+data.TokenId+'</strong> </p><br><button class="btn btn-primary close-button" type="submit">Submit Another Ticket</button>');
            error:       function (err) {
                var errorMsg = 'Issue Submission Failed ! ' + err.statusText;

Server Side:-

Nothing special was done at the server end of email sending, only attachments were handled in more generic way.

        attachments: (f) {
    return   {
        filePath: f.path,
        cid:      f.path

Also this code was useful to delete those temp files from your temp folder after attachments are mailed,

  /* Clean up the temporary files. */
    Attachments.forEach(function (f) {

and that's how was email sending code was called,so that BodyParser() and multipart() both could be used.'/api/contactus/', express.multipart(), api_calls.contactUs);