I found that uploading image with AJAX doesn't seem working with multipart as specified in the form, because my code for checking if it's multipart() never works (in Java);
if (context.isMultiPart()
{
System.out.println("received Multipart data");
}
else
{
System.out.println("not multipart data!"); /* my code always prints this message in the upload handler uploadPost() */
}
I have this html form:
<div class="title"><label>Upload picture!</label></div>
<form method="post" id="imageUploadForm" enctype="multipart/form-data" action="/uploadPost">
Please specify file to upload: <input type="file" name="upfile"><br />
<input type="submit" value="submit" id="submitButton">
</form>
<div id="imagedisplay">
</div>
and the following is my ajax code that sends the image to the upload handler at the address /uploadPost
. The uploadPost() method in my Java code first determines whether the upload is multipart or not, however, it seems that ajax does not send the image as multipart. Is it because I use jQuery's serialize() method on the form?
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#imageUploadForm').submit(function(evt) {
var formData = $('#imageUploadForm').serialize();
$.post('/uploadPost', formData, uploadResults);
evt.preventDefault();
});
// display the uploaded image on the same page
function uploadResults(data) {
$('#imagedisplay').html("<img src=" + data.url + "" + data.name + ">");
} // end of uploadResults
}); // end of ready
</script>
The serialize() method creates a URL encoded text string by serializing form values. You can select one or more form elements (like input and/or text area), or the form element itself. The serialized values can be used in the URL query string when making an AJAX request.
The serializeArray() is an inbuilt method in jQuery which is used to create a JavaScript array of objects that is ready to be encoded as a JSON string. It operates on a jQuery collection of forms and/or form controls. The controls can be of several types.
Changing from serialize() to the following code works for me:
$('#imageUploadForm').submit(function(evt) {
evt.preventDefault();
var formData = new FormData(this);
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
success: function(data) {
$('#imagedisplay').html("<img src=" + data.url + "" + data.name + ">");
},
error: function(data) {
$('#imagedisplay').html("<h2>this file type is not supported</h2>");
}
});
});
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