'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 1:[1]
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);
Solution 2:[2]
const getFormDataSize = (formData) => [...formData].reduce((size, [name, value]) => size + (typeof value === 'string' ? value.length : value.size), 0);
//Usage
const formData = new FormData();
formData.append('field0', '...');
formData.append('field2', new File(['...'], 'file.txt'));
formData.append('field1', new Blob(['...']));
console.log('%i Bytes', getFormDataSize(formData));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
