Search code examples
jqueryajaxjquery-file-upload

Multipart file upload using jQuery


Is there any way to upload multipart file using jQuery in JSP + java. Getting error while doing in jQuery AJAX.

$.ajax({
    type: "POST",
    url: "${pageContext.request.contextPath}/users/imageUpload/" + $imageUpload + "/" + $userId‌​,
    contentType: "multipart/form-data",
    processData: false,
}).done(function(data) {}).fail(function(data) {
    alert("Ooopss..! Something Bad Happened.!");
});

Solution

  • $("input:file").change(function(objEvent) {
        var objFormData = new FormData();
        // GET FILE OBJECT 
        var objFile = $(this)[0].files[0];
        // APPEND FILE TO POST DATA
        objFormData.append('userfile', objFile);
        $.ajax({
            url: 'Here Your Server-Url'
            type: 'POST',
            contentType: false,
            data: objFormData,
            //JQUERY CONVERT THE FILES ARRAYS INTO STRINGS.SO processData:false
            processData: false,
            success: function(data) {}
        });
    });