如何获取FormData对象的长度

Pao*_*ssi 7 ajax jquery

我正在使用ajax上传文件。为了传递和保存数据,我使用 FormData 对象。我想显示 FormData 对象的长度,但我做不到。

我尝试过这种方式

 var data = new FormData();
 jQuery.each($(this)[0].files, function(i, file) {
     data.append('img['+i+']', file);
 });

 /* FIRST */
 var getObjectSize = function(obj) {
    var leng = 0, key;
    for (key in obj) {
      if (obj.hasOwnProperty(key)) leng++;
    }
    return leng;
 };
 var items = getObjectSize(data);
 alert(items); // output 0

 /* SECOND */
 var items = Object.keys(data).length;
 alert(items); // output 0
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?谢谢。

Run*_*orn 2

当您使用 console.log(formData) 时,Formdata 看起来像这样,

FormData {
     append: function
 }
 __proto__: FormDataappend: function append() {
     [native code]
 }
 arguments: nullcaller: nulllength: 2name: "append"
 __proto__: function Empty() {}
 apply: function apply() {
     [native code]
 }
 arguments: nullbind: function bind() {
     [native code]
 }
 call: function call() {
     [native code]
 }
 caller: nullconstructor: function Function() {
     [native code]
 }
 length: 0name: "Empty"
 toString: function toString() {
     [native code]
 }
 __proto__: Object < function scope > < function scope > Global: Windowconstructor: function FormData() {
     [native code]
 }
 __proto__: Object__defineGetter__: function __defineGetter__() {
     [native code]
 }
 __defineSetter__: function __defineSetter__() {
     [native code]
 }
 __lookupGetter__: function __lookupGetter__() {
     [native code]
 }
 __lookupSetter__: function __lookupSetter__() {
     [native code]
 }
 constructor: function Object() {
     [native code]
 }
 hasOwnProperty: function hasOwnProperty() {
     [native code]
 }
 isPrototypeOf: function isPrototypeOf() {
     [native code]
 }
 propertyIsEnumerable: function propertyIsEnumerable() {
     [native code]
 }
 toLocaleString: function toLocaleString() {
     [native code]
 }
 toString: function toString() {
     [native code]
 }
 valueOf: function valueOf() {
     [native code]
 }
 get __proto__: function __proto__() {
     [native code]
 }
 set __proto__: function __proto__() {
     [native code]
 }
Run Code Online (Sandbox Code Playgroud)

因此,无法询问已存储到的数据FormData。而且,官方文件也提到了同样的事情。

因此,为什么不直接计算文件数量来获取 length 呢?

var length=$(this).get(0).files.length
Run Code Online (Sandbox Code Playgroud)

PS:您可以通过此问题/答案获得更多详细信息。