简体   繁体   中英

how to pass file to controller using jquery ajax serialize() in spring mvc

Here is my ajax

 $("#btnFinish").click(function(event) {
              event.preventDefault();
              var data = $("#client-maint-form").serialize();
               $.ajax({
                      type: 'POST',
                      url: "sabb/saveMe",
                      data: data,
                      dataType: "json",
                      contentType: 'multipart/form-data',
                      success: function(resdata, textStatus, jqXHR) {
                          alert("success");
                      },
                      error: function(jqXHR, textStatus, errorThrown) {
                          alert("Server Exception");
                      }

                      });
 });

Please help me pass file to controller...thanks in advance

As my understanding, you would like to upload a file using Spring and Ajax. I think the easiest way is to use MultipartHttpServletRequest in Server side. For example, in server side you can do like:

 UploadedFile ufile;//UploadedFile is a custom object to keep the file 

 @RequestMapping(value = "/upload", method = RequestMethod.POST)
   public @ResponseBody String upload(MultipartHttpServletRequest request, HttpServletResponse response) {                 


     Iterator<String> itr =  request.getFileNames();

     MultipartFile mpf = request.getFile(itr.next());
     System.out.println(mpf.getOriginalFilename() +" uploaded!");

     try {
        //file information
        ufile.length = mpf.getBytes().length;
        ufile.bytes= mpf.getBytes();
        ufile.type = mpf.getContentType();
        ufile.name = mpf.getOriginalFilename();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

       return "success";

  }

in html file:

  <form id="form2" method="post" action="/spring-mvc-ajax/upload/upload" enctype="multipart/form-data">
  <!-- File input -->    
  <input name="file2" id="file2" type="file" /><br/>
</form>

<button value="Submit" onclick="uploadJqueryForm()" >Upload</button><i>Using JQuery Form Plugin</i><br/>

In script, you can use ajax with FormData

//using FormData() object
function uploadFormData(){
    $('#result').html('');

  var oMyForm = new FormData();
  oMyForm.append("file", file2.files[0]);

  $.ajax({
    url: 'http://localhost:8080/spring-mvc-ajax/upload',
    data: oMyForm,
    dataType: 'text',
    processData: false,
    contentType: false,
    type: 'POST',
    success: function(data){
      $('#result').html(data);
    }
  });
}

Hope it help!

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