Search code examples
javascript

JS How to measure size of FormData object?


I need some decision how to measure the size of FormData before send. I haven't find anything in Internet on plain JS. In formdata could be files and text fields

I need to know size in bytes and also length


Solution

  • You can use Array.from(), FormData.prototype.entries() to iterate .length or .size

    var fd = new FormData();
    fd.append("text", "abc");
    fd.append("file0", new Blob(["abcd"]));
    fd.append("file1", new File(["efghi"], "file.txt"));
    
    var res = Array.from(fd.entries(), ([key, prop]) => (
                {[key]: {
                  "ContentLength": 
                  typeof prop === "string" 
                  ? prop.length 
                  : prop.size
                }
              }));
    
    console.log(res);