how to pass input type file data in ajax call

前端 未结 3 1335
死守一世寂寞
死守一世寂寞 2020-12-06 08:43

I\'ve my form

\" method=\"post\"> Photo <
相关标签:
3条回答
  • 2020-12-06 09:15

    Try this one:

    $.ajax( {
      type: 'POST',
      url: 'process.php',
      data: new FormData( this ),
      processData: false,
      contentType: false,
      cache: false,
      success: function(data){
      }
    });
    
    0 讨论(0)
  • 2020-12-06 09:16

    This is impossible.

    Sending data via an ajax call is not supported from browsers.

    The accepted workaround is to post the file in a hidden iframe in the background (so it looks like ajax). The solution here is to find your 'ajax file upload' library of choice and use that to upload the file.

    0 讨论(0)
  • 2020-12-06 09:17

    Well i have tried something like this with firefox and chrome:

    <form id="guestForm" action="<?php echo $_SERVER["PHP_SELF"];?>" method="POST" enctype="multipart/form-data">
       <input type="file" id="fileInput" name="fileInput" />
       <input type="button" value="submit" id="ajaxSubmit" />
    </form>
    <script type="text/javascript">
        $(function () {
            $("#ajaxSubmit").click( function () {
                var fd = new FormData();
    
                fd.append( "fileInput", $("#fileInput")[0].files[0]);
                $.ajax({
                    url: 'process.php',
                    type: 'POST',
                    cache: false,
                    data: fd,
                    processData: false,
                    contentType: false,
                    beforeSend: function () {
                        $("#output").html("Uploading, please wait....");
                    },
                    success: function () { 
                        $("#output").html("Upload success.");
                    },
                    complete: function () {
                        $("#output").html("upload complete.");
                    },
                    error: function () {
                        alert("ERROR in upload");
                    }
                });
    
            });
        });
    </scirpt>
    

    I originally had this code in tandem with Java as the server side code. Although, i don't see why this wouldn't work with PHP. But, your question is how to pass input type file data in an ajax call. So this is how i did it.

    0 讨论(0)
提交回复
热议问题