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.
Fixing 415 Unsupported Media Type errorsEnsure that you are sending the proper Content-Type header value. Verify that your server is able to process the value defined in the Content-Type header. Check the Accept header to verify what the server is actually willing to process.
The HTTP 415 Unsupported Media Type client error response code indicates that the server refuses to accept the request because the payload format is in an unsupported format. The format problem might be due to the request's indicated Content-Type or Content-Encoding , or as a result of inspecting the data directly.
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(...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With