jQuery:FormData()不起作用

时间:2016-10-29 04:49:46

标签: jquery

我做了一个非常简单的例子来测试jQuery' s FormData是否有效。

HTML

<form id="frm" action="/fileupload" method="post">
<input type="file" name="uploadfile" />
<input type="file" name="uploadfile" />
<input type="button" id="uploadbutton" value="클릭" />
</form>

我导入jQuery cdn:

<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>

我从电脑中选择一些图像文件。

并在Chrome development tool中执行以下代码:

>> var form = $('#frm');
>> form

<form id="frm" action="/fileupload" method="post">
<input type="file" name="uploadfile" />
<input type="file" name="uploadfile" />
<input type="button" id="uploadbutton" value="클릭" />
</form>


>> var formData = new FormData(form);
>> formData

它只显示,

FormData {}

它不包含任何值。它是空的。为什么不起作用?

2 个答案:

答案 0 :(得分:0)

我估计,你应该尝试传递元素本身,而不是jQuery对象:

var formData = new FormData(form[0]);

答案 1 :(得分:0)

我认为您需要调用FormData.append方法将文件添加到FormData对象。

这是我向服务器提交带有ajax的FormData对象的示例代码。

<html>
    <head>
        <script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>

    </head>
    <body>
        <div id="main">
           <input type="file" id="file-select" multiple webkitdirectory/>

           <button id="btn-upload" ><span class="glyphicon glyphicon-upload"></span> Upload</button>
        </div>

        <script>
          var fileSelect = document.getElementById('file-select');


          $(document).ready(function () {

             //Listen the upload button onclick
             $('#btn-upload').on("click",function(){

            event.preventDefault();

            //Check if contains files to upload

            if(fileSelect.files.length != 0){

                //Declare a FormData Object to pass the files
                var formData = new FormData();
                var fileCount = fileSelect.files.length;

                //Add the files from file-select into FormData                  
                for (var i = 0; i < fileCount; i++)
                {
                    var file = fileSelect.files[i];
                    formData.append("FileUpload", file);
                }

                //Make the ajax post request with FormData to your destination(eg:webservice or php page)

                $.ajax({
                    type: 'POST',
                    url: 'http://yourhost:port/something.php', 
                    data: formData,
                    contentType:false,
                    processData: false,
                    success: function (data) {
                        //Do the next process u want
                    },
                    error: function(err){
                        //Process the error
                    }

                });
            }

         });
      });
      </script>
     </body>
  </html>

希望这对您的FormData用法很有用。