1

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.!");
});
4
  • 1
    Can you show, what you have tried so far? Commented Dec 17, 2015 at 5:16
  • $.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.!"); }); Commented Dec 17, 2015 at 5:17
  • also not getting the value in form serialize Commented Dec 17, 2015 at 5:18
  • This comment should go as update to the question. Also, share the server side code that accepts the AJAX request. Commented Dec 17, 2015 at 5:18

2 Answers 2

7
$("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) {}
    });
});
Sign up to request clarification or add additional context in comments.

4 Comments

@RequestMapping("/imageUpload/{image}/{userId}") public String formForImageUpload(Model model, @PathVariable("image") MultipartFile image, @PathVariable("userId") Integer userId ) { Users users = new Users(); model.addAttribute("users", users); return null; }
above mentioned code is am using in java controller
@Ali, Better to add some description, rather tossing up the code out there.
How i will get the FormData in controller?
1

Try this:

var data = new FormData(document.getElementById("yourFormID")); // your form ID
var url = jQuery("#yourFormID").attr("action"); // your form action 
$.ajax({
    url: url,
    type: "POST",
    data: data, // this will get all the input fields of your form.
    enctype: 'multipart/form-data',
    processData: false,  // tell jQuery not to process the data
    contentType: false,   // tell jQuery not to set contentType
    dataType: 'json', // as you want
    success: function(response) {        
        // success 
    }
});  // JQUERY Native Ajax End

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.