douhe6255
douhe6255
2017-09-05 11:06

使用AJAX上传文件无法正常工作

已采纳

i'm trying to recreate this guide from olanod answer but isn't working for me.

I want to upload a file using AJAX but i'm getting an empty $_POST:

<form enctype="multipart/form-data">
        <input type="file" name="file"> 
        <br>
        <input type="text" name="as" value="asd">
        <!--<button type='button' class="add_more">Add More Files</button>-->
<input type="button" value="Upload" />
</form>

and this is my script (copy paste from olanod answer ):

<script>
        $(document).ready(function(){
          /*  $('.add_more').click(function(e){
                e.preventDefault();
                $(this).before("<input name='upfile[]' type='file'/><br>");
            });*/

            $(':button').on('click', function() 
            {
                $.ajax({
                    // Your server script to process the upload
                    url: 'ajax.php',
                    type: 'POST',

                    // Form data
                    data: new FormData($('form')[0]),

                    // Tell jQuery not to process data or worry about content-type
                    // You *must* include these options!
                    cache: false,
                    contentType: false,
                    processData: false,

                    // Custom XMLHttpRequest
                    xhr: function() {
                        var myXhr = $.ajaxSettings.xhr();
                        if (myXhr.upload) {
                            // For handling the progress of the upload
                            myXhr.upload.addEventListener('progress', function(e) {
                                if (e.lengthComputable) {
                                    $('progress').attr({
                                        value: e.loaded,
                                        max: e.total,
                                    });
                                }
                            } , false);
                        }
                        return myXhr;
                    },
                });
            });
        });
</script>

As i said, i'm tring to see what i'm taking and this is the result from my php file:

array(1) { ["as"]=> string(3) "asd" }

I returned a text field to be sure.

P.D: Sorry for my english. I hope you can understand me, i'm trying my best!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • doujiao1814 doujiao1814 4年前

    As @user2486 said,

    You should use $_FILES not $_POST – user2486

    He is right.

    点赞 评论 复制链接分享
  • drr47973 drr47973 4年前
    Check this one..
    
     <!DOCTYPE html>
        <html lang="en">
            <head>
                <title>Ajax Image Upload</title>
                <meta charset="utf-8">
                <meta name="viewport" content="width=device-width, initial-scale=1">
                <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
                <script src="../js/jquery-3.1.1.min.js"></script>
                <script src="../js/validator.js"></script>
                <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
            </head>
            <body>
    
                <div class="container">
                    <span id="msg"></span>
                    <h2>Image Upload Form</h2>
                    <form data-toggle="validator" role="form" name="image-form" method="post" enctype="multipart/form-data" id="my-form" action="<?php $_SERVER['PHP_SELF']; ?>">
                        <div class="form-group">
                            <label for="image">Image:</label>
                            <input type="file" id="image"  name="image[]" data-error="Upload Image" multiple required>
                            <div class="help-block with-errors"></div>
                        </div>    
                        <button type="submit" class="btn btn-default">Submit</button>
                    </form>
                </div>
    
            </body>
        </html>
    
    
        <script type="text/javascript">
           $(document).ready(function (e) {
                $("#my-form").on('submit', (function (e) {
                    e.preventDefault();
                    var formData = new FormData(this);            
                        $.ajax({
                            url: "upload.php",
                            type: "POST",
                            data: formData,
                            contentType: false,
                            cache: false,
                            processData: false,
                            success: function (data) {
                                $("#my-form")[0].reset();
                                //alert(data);
                                $("#msg").html(data);
                            },
                        });
    
                    return false; //IE
                }));
            });
        </script>
    
    点赞 评论 复制链接分享
  • duande1986 duande1986 4年前

    you can use this method to upload file

    html-
    
    <input type="file" class="btn btn-default" name="img2" id="img2" />
    
    javascript-
    
    var formData = new FormData();
              formData.append('Photo', $('#img2')[0].files[0]);
              $.ajax({
                  url: 'ImgUpload.php',
                  data: formData,
                  type: "POST",
                  // THIS MUST BE DONE FOR FILE UPLOADING
                  contentType: false,
                  processData: false,
                  
              }).done(function( msg ) {

    </div>
    
    点赞 评论 复制链接分享