10

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>
TonyW
  • 18,375
  • 42
  • 110
  • 183

2 Answers2

32

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>");
                }
                });
            });
TonyW
  • 18,375
  • 42
  • 110
  • 183
1

You can make use of Formdata() , API DOC

The code will be similar to the the answer given in the existing question Stack Overflow Link

Community
  • 1
  • 1
Jayaram
  • 1,715
  • 18
  • 30