简体   繁体   中英

is this ajax call for below rest Service is correct or not?

Sample rest Service is below:

@RequestMapping(value = "/image/upload", method = RequestMethod.POST)
public void uploadImage(@RequestParam("image") MultipartFile fileObj)
        throws Exception 
{
  System.out.print("File Name:"+fileObj.getOriginalFileName()); 

}

and i wrote ajax code like this : and my accept application format is Json when i call this i get 400 error

            $('#user_click').click(function(){
    var data = { 
              image:$("#file_1").val
                };
    $.ajax({
        url : "http://localhost:8080/MyProject/image/upload",
        type : "POST",
        contentType : false,
        crossDomain : true,
        data : JSON.stringify(data),
        dataType : 'json',
        async : true,
        success : function(result) {
            alert('The Selected Items uploaded');
        },
        error: function(message){
          alert("Error:"+JSON.stringify(message));  
        }
       });

is this ajax code is correct or not?

No, it will not work since ajax request will not transfer file data.

The solutions are

  1. Use a file upload plugin like jquery-form

Ex:

$('#myForm').ajaxSubmit({
    url : 'http://localhost:8080/MyProject/image/upload',
    type : "POST",
    dataType : "json",
    success : function(response) {

    },
    error : function(response) {

    }
});
  1. Use html5 FormData (Sadly no IE support)

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