简体   繁体   中英

form data along with file upload with Ajax and spring

i am using spring , Ajax and trying to upload file along with other data

 if(form.field_UploadFile != undefined){
        formContent.field_UploadFile=$( form.field_UploadFile  )[0].files[0];
        }
   var fields ={};
   for(var i=0; i<form.elements.length; i++){
       if (form.elements[i].name){
       if(form.elements[i].name.substring(0,6)=="field-"){
           if(form.elements[i].type=='checkbox'){
              if(form.elements[i].checked){
                   fields[form.elements[i].name]='checked';
               }else{
                   fields[form.elements[i].name]='unchecked';
               }
           }else{
                fields[form.elements[i].name]=form.elements[i].value;
           }
       }
       }
   }

   $.ajax({  
       type: "POST",  
       url: "${pageContext.request.contextPath }/forms/createnocaptcha",
       data: formContent,  
       dataType: "json",  
       contentType: false, 
       processData: false,

       complete: function (xhr, status) {
            $('html, body').animate({ scrollTop: 0 }, 0);              
            if (status === 'error' || !xhr.responseText) {
                //alert("error");
                $("#" + messagedivid).addClass("errorMessage");
                $("#" + messagedivid).html("Form sunewsbmission error");
            }
            else {
                var data = xhr.responseText;
                //$("#" + messagedivid).addClass("successMessage");
                //$("#" + messagedivid).html(data);
                $("#" + feedbackdivid).addClass("successMessage");
            $("#" + feedbackdivid).show();
            $("#" + messagedivid).hide();
            $(form)[0].reset();
            }

controller

@RequestMapping(value = "/forms/createnocaptcha", method=RequestMethod.POST)
@ResponseBody
public String createPageNoCaptcha( Form formContent, HttpServletRequest request, HttpSession session){
    boolean status = false;

If i put requestBody for formContent then i get 415 unsupported media and if it is removed then the form values are null.

And also can I use same controller for both Multi part and non multipart.

Please advise

Thanks

We need to convert js object to JSON string before sending it.

Change your data in ajax call like this,

data: JSON.stringify(formContent), 

and then use @RequestBody Form formContent And change contentType in Ajax call to application/json

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM