Govinda Sakhare
Govinda Sakhare

Reputation: 5729

Spring mvc ajax file upload leading to 415 (Unsupported Media Type)

I am trying fileupload using jquery ajax method. but it is leading to 415 (Unsupported Media Type) error on client side.but with non-ajax request my code is working fine.

My controller code.

@RequestMapping(value = "/imageUpload", headers = "content-type=multipart/*", method = RequestMethod.POST, consumes = "application/json")
public @ResponseBody
String uploadImage( @RequestParam("fileData") MultipartFile multipartFile, HttpServletRequest request )
{
       // statements
}

my view page

<form id="uploadForm" action="imageUpload" method="post" enctype="multipart/form-data">
    <div>
        <input type="file" id="fileData" name="fileData" />
        <input type="submit" id="submitContent"  value="upload" />
    </div>
 </form>

and ajax call.

$("#uploadForm").submit(function (e) {
     e.preventDefault();
                var $form = $("#uploadForm");                 
                $.ajax({
                  type: $form.attr('method'),
                  url: $form.attr('action'),                 
                  data: $form.serialize(),
                  dataType : 'json',
                  enctype: 'multipart/form-data',
                  processData: false,                     
                  success: function(msg){
                        $( "#editor" ).append(msg);
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) { 
                        alert("Status: " + XMLHttpRequest);   alert("Status: " + textStatus); alert("Error: " + errorThrown); 
                    }
                  });
 });

I have tried several things like setting contentType:false . so please suggest me any changes if required.

Upvotes: 8

Views: 6556

Answers (1)

Rafik BELDI
Rafik BELDI

Reputation: 4158

Take a look at this Sending files using a FormData object

Data from file element is not serialized, use new FormData() to initialize the data and then add your form elements including the data element. This code will work

    $("#uploadForm").submit(function(e) {
    e.preventDefault();
    var $form = $("#uploadForm");
    var fd = new FormData($(this)[0]);
    console.info(fd);
    $.ajax({
        type : 'POST',
        url : $form.attr('action'),
        data : fd,
        cache : false,
        processData : false,
        contentType : false,
        success : function(response) {
            console.info(response);
        },
        error : function(XMLHttpRequest, textStatus, errorThrown) {
            console.info("Status: " + XMLHttpRequest);
            alert("Status: " + textStatus);
            alert("Error: " + errorThrown);
        }
    });
});

To add other form variables use fd.append(...)

Upvotes: 3

Related Questions