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

标签 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

它适用于除"file"输入之外的所有表单字段。它无法获取我尝试在名为"file"类型的“imgFile”输入中传递的文件对象。我做了一些搜索,偶然发现了 FormData 函数。我像这样重写了函数:

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

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

Debugging enter image description here

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

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

最佳答案

您可以像这样尝试使用 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

关于javascript - 获取包含文件输入的表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30383496/

相关文章:

html - 鼠标悬停在 d3 圆环图上时图例文本背景发生变化

jquery - 嵌入式 Youtube 视频的缩略图模糊

javascript - Fancybox 在第二次点击时响应并且不切换到下一张图片

jQuery DataTables 可编辑 - 空值时只读

javascript - 如何在免费 jqgrid 中单击复选框列开始内联编辑

javascript - 如何在后台运行 android phonegap 应用程序(关闭应用程序后)?

javascript - 在 JavaScript 中封装回调

javascript - 循环问题 javascript 将无法运行

javascript - 如何动态删除嵌套的json键?

jquery - 元素在 Joomla 的类别页面布局中重叠(由于容器高度属性)