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

链接地址: http://www.djcxy.com/p/48716.html

上一篇: 使用角厂服务和$资源将分段上传到Spring Rest

下一篇: 使用Ajax和Spring构建数据以及文件上传