获取包含文件输入的表单的数据

时间:2015-05-21 20:13:52

标签: javascript jquery html forms

我有以下html表单:

<form method="post" class="treeWidgetForm" enctype="multipart/form-data">
                                <div class="row">
                                    <label>Photo :</label> <br/>
                                    <input type="file" name="imgFile">
                                </div>
                                <div class="row">
                                    <label>Firstname :</label> <br/>
                                    <input type="text" name="firstname" class="treeWidgetInput"/>
                                </div>

                                <div class="row">
                                    <label>Lastname :</label> <br/>
                                    <input type="text" name="lastname" class="treeWidgetInput"/>
                                </div>

                                <div class="row">
                                    <label>Gender :</label> <br/>
                                    <label class="treeWidgetRadio"><input type="radio" name="gender" value="male">Male
                                    </label>
                                    <label class="treeWidgetRadio"><input type="radio" name="gender"
                                                                          value="female">Female
                                    </label>
                                </div>

                                <div class="row">
                                    <label>Birth date :</label> <br/>
                                    <input id="birthdate" type="text" name="birthdate" class="treeWidgetInput"/>
                                </div>

                                <div class="row">
                                    <label>Death date :</label> <br/>
                                    <input id="deathdate" type="text" name="deathdate" class="treeWidgetInput"/>
                                </div>

                                <div class="row">
                                    <label>Nationality :</label> <br/>
                                    <select name="nationality" class="treeWidgetInput"></select>
                                </div>

                                <div class="row">
                                    <label>Country :</label> <br/>
                                    <select name="country" class="treeWidgetInput"></select>
                                </div>

                                <div class="row spaced">
                                    <div class="col-lg-12">
                                        <button type="reset" class="btn btn-default treeWidgetFormBtn"
                                                data-operation="cancelPerson">Cancel</button>
                                        <button type="submit" class="btn btn-primary treeWidgetFormBtn"
                                                data-operation="savePerson">Save</button>
                                    </div>
                                </div>
                            </form>

我需要获取此表单中包含的数据,以便我可以通过AJAX请求将其发送到服务器。我编写了以下javascript函数,它接收表单元素作为参数:

FormUtils.getFormData = function(form) {
  var data = {};
  $(form).serializeArray().
      map(function (x) {
         data[x.name] = x.value;
      });
  return data;
};

enter image description here

它适用于所有表单字段,除了&#39;文件&#39;输入。它无法获取我尝试在名为&#39; imgFile&#39;的输入中传递的文件对象。类型&#39;文件&#39;。我做了一些搜索并偶然发现了FormData函数。我重写了这个函数:

FormUtils.getFormData = function(form) {
    var data = new FormData($(form)[0]);
    return data;
}; 

FormData函数返回一个空对象。以下是一些Chrome调试屏幕截图:

Debugging enter image description here

我不明白为什么FormData会创建一个空对象。我可以从调试器中看到&#39;形式&#39;我传递给函数的对象是一个表单元素。我应该如何创建我的数据对象,以便我可以像这样发送它:

$.ajax({
        url: url,
        data: dataObj,
        type: "PUT",
        processData: false,
        contentType: false
});

1 个答案:

答案 0 :(得分:2)

您可以尝试这样的FileReader API。

<!DOCTYPE html>
<html>
<head>
<script>        
  function handleFileSelect()
  {               
    if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
      alert('The File APIs are not fully supported in this browser.');
      return;
    }   

    input = document.getElementById('fileinput');
    if (!input) {
      alert("Um, couldn't find the fileinput element.");
    }
    else if (!input.files) {
      alert("This browser doesn't seem to support the `files` property of file inputs.");
    }
    else if (!input.files[0]) {
      alert("Please select a file before clicking 'Load'");               
    }
    else {
      file = input.files[0];
      fr = new FileReader();
      fr.onload = receivedText;
      //fr.readAsText(file);
      fr.readAsDataURL(file);
    }
  }

  function receivedText() {           
    //result = fr.result;
               document.getElementById('editor').appendChild(document.createTextNode(fr.result))
  }           

</script>
</head>
<body>
<input type="file" id="fileinput"/>
<input type='button' id='btnLoad' value='Load' onclick='handleFileSelect();'>
<div id="editor"></div>
</body>
</html>  

你可以在这里找到一些知识:
http://www.htmlgoodies.com/beyond/javascript/read-text-files-using-the-javascript-filereader.html#fbid=59bT9DGXOkX