Uploading image by AJAX, cannot use the serialize() method in jQuery?

ぐ巨炮叔叔 提交于 2020-01-12 14:44:54

问题


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>

回答1:


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>");
                }
                });
            });



回答2:


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



来源:https://stackoverflow.com/questions/24268931/uploading-image-by-ajax-cannot-use-the-serialize-method-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!