Search code examples
jquerynode.jstwitter-bootstrapmulter

nodejs multer with jquery steps wizard and bootstrap fileuploader


I'am having trouble uploading multiple files in my jquery wizard. The wizard contains multiple fields that is being sent to the server (nodejs) correctly, but it seems that no matter what I do, the files are undefined.

Here is some code snippets:

<form id="wodcreate" class="steps-validation" action="#" enctype="multipart/form-data">

...

<div class="form-group">
    <div class="col-lg-10">
        <input type="file" id="images" name="images" class="file-input" accept="image/*" multiple="multiple">
        <span class="help-block" data-i18n="general.Only-images-allowed">Only images are allowed. Maximum size of each image is 5 MB, and there is a maximum of 10 images.</span>
    </div>
</div>

...

app.post('/api/user/create', upload.any(), function (req, res, next) {
    //Pass the logic to a dedicated function
    console.log(req.body);
    console.log(req.files);
    res.json({success : "Updated Successfully", status : 200});
});

I use formdata when posting to the server, and because i use a wizard, I dont use the jquery uploader button, but adds the images to formdata with this method:

$('#images').on('filebatchpreupload', function(event, data, previewId, index) {
var form = data.form, files = data.files, extra = data.extra,
    response = data.response, reader = data.reader;

$.each(files, function (key, value) {
    if(value != null){
        formData.append("images", value, value.name);
    }
});

The onFinished function in the wizard looks like this:

onFinished: function (event, currentIndex) {

    var res = $(".steps-validation").valid();
    var model_data = $(".steps-validation").serializeArray();

    //For all normal input fields
    $.each(model_data,function(key,input){
        formData.append(input.name,input.value);
    });
    //For videolist (li nonform fields):
    $('#videolist li').each(function(){
        formData.append('videolist[]',$(this).attr("id"));
    });

    //For wysiwyg
    var desc = CKEDITOR.instances.desc.getData();
    formData.append('desc',desc);

    if (res == true) {
        jQuery.ajax({
            type: "POST",
            url: "/api/user/create",
            data: formData,
            processData: false,  // tell jQuery not to process the data
            contentType: false,   // tell jQuery not to set contentType
            success: function (data) {
                if(data.status == 200){

                }
            }
        });
    }
    return res;
}

Solution

  • After some time, i finally figured out that the error was due to the function:

    $('#images').on('filebatchpreupload')
    

    Was not being triggered.