Reputation: 63
I wanna send an image through ajax but I get the following exception:
org.apache.commons.fileupload.FileUploadBase$InvalidContentTypeException: the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is false
surprisingly when I send this form regularly(not through ajax) form works fine.I tried changing Content-Type to multipart/form-data but then I get this exception:
org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found
here is the jquery code:
$(document).ready(function() {
$("#myform").submit(function(e) {
e.preventDefault();
var data = new FormData();
data.append('file', document.formName.file.files[0]); // <-- possibly this line doesn't work
$.ajax({
url: 'upload.do',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(res) {
}
});
});
});
and the form:
<form name="formName" enctype="multipart/form-data" id="myform" action="upload.do" method="POST">
<input type="file" name="file" id="input-file" />
<br>
<input type="submit" value="Upload images" class="upload" />
</form>
Upvotes: 1
Views: 6169
Reputation: 22992
Try this:
$(document).ready(function() {
$('.upload').click(function() {
var input = document.getElementById('input-file');
file = input.files[0];
var data = new FormData();
data.append('file', file);
$.ajax({
url: 'upload.do',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(res) {
}
});
});
});
Upvotes: 2