Question

I am trying to parse a multipart/form-data sent from $.ajax() and on the server side data is coming in req.body not in req.files as stated in the documentation of express.

What I am trying to do is sending multiple image files and form data through $.ajax,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) {
    e.preventDefault();
    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());

    $.ajax({
        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");
            console.dir(data);
        },
        error: function (err) {
            console.log('error  in AJAX');
            console.log(err);
        }
    });
});

Server Side API handling the Request:-

function contactUs (req, res, next) {

    console.log("TESTING Body ");
    console.dir(req.body);

    console.log("TESTING Files");
    console.dir(req.files);

    var Transport   = email.createTransport("SMTP", {
        service: "Gmail",
        auth: {
            user: "dummy@dummy.com",
            pass: "dumy1234"
        }
    });

    Transport.sendMail({
        host    : "smtp.gmail.com",
        port    : "587",
        domain  : "domain.com",
        to      : "dummy@dummy.com",
        from    : "dummy@dummy.com",

        subject : "[Technical Support] "+EmailInfo.Name + " Submitted an Issue!",
        reply_to: req.body.Email,
        html    : "<h2 >Message Details</h2>",
        authentication : "login",
        username: 'dummy@dummy.com',
        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 app.use(express.multipart()); , but when I inserted it in my app.js it gave me 400 bad request ,and didn't even executed the contactUs function.

Was it helpful?

Solution

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]);
        }
        $.ajax({
            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;
                $('#result').removeClass('alert-success').addClass('alert-error').html(errorMsg).show();
            }
        });
    }

Server Side:-

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

        attachments:    Attachments.map(function (f) {
    return   {
        fileName: f.name,
        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) {
    fs.unlinkSync(f.path);
    });

and that's how was email sending code was called,so that BodyParser() and multipart() both could be used.

app.post('/api/contactus/', express.multipart(), api_calls.contactUs);

OTHER TIPS

$.ajax({     
     type: "POST",
     url: '/admin/systemgoalssystemgoalupdate?format=html',
     data: formdata,
     success: function (data) {
         console.log(data);
     },
     dataType: "json"
 });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top