Search code examples
javajavascriptjqueryajaxmultifile-uploader

how to send multipart/form-data request in ajax


The below function wont work. i want to upload multiple files & request submit by ajax.here content type occur "text/plain;charset=UTF-8" i want to change content type="multipart/form-data" the following functions shown below.plz give any suggestions

function importNow(serverURL, parameters) {
        document.body.style.cursor = "wait";
            $.ajax({
            url: serverURL,
            data: parameters,
            processData: false,
            contentType: false,
            type: "POST",
            cache: false,
            dataType: "text",
            success: function(data) {
                if ($.trim(data) === "Success") {
                    updateStatusMessage("success", "Import scenario successfully");
                } else {
                    updateStatusMessage("failure", $.trim(data));
                }
                document.body.style.cursor = "default";
            },
            async: false
        });
    }



 function importScenario() {
        var serverURL = homeURL + "/runapp";
        var parameters = "requestType=Import&subRequestType=importScenario&userName=" + userName ;
         refButton = '<form id="importForm" class="userInputForm" enctype="multipart/form-data">' +
         '<input id="file" name="file" type="file" />' +
         '</form>';
         document.getElementById("popupDiv").innerHTML = refButton;
         $("#popupDiv").dialog({
             title: "Import Scenario",
             draggable: true,
             bgiframe: true,
             modal: true,
             width: 500,
             heigth: 100,
             show: {effect: 'blind', duration: 500},
             hide: {effect: 'fade', duration: 1000},
             zIndex: 1000,
             buttons: {
                 'Upload': function() {
                     if ($("#importForm").valid()) {
                         parameters; 
                         importNow(serverURL, parameters);
                         $(this).dialog("close");
                     }
                 },
                 'Cancel': function() {
                     $(this).dialog("close");
                 }
             }
         });
    }

Solution

  • You'll have to use a FormData object to do a multipart/form-data ajax request

    var parameters = new FormData();
    parameters.append("requestType","Import"); 
    parameters.append("subRequestType","importScenario"); 
    parameters.append("userName",userName ); 
    ...
        importNow(serverURL, parameters);