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
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
Share Improve this question edited Feb 15, 2017 at 19:21 Nikolai asked Feb 15, 2017 at 19:16 NikolaiNikolai 1951 gold badge1 silver badge13 bronze badges 3 |3 Answers
Reset to default 17You 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);
var size = 0;
for(var e of formData.entries()) {
size += e[0].length;
if (e[1] instanceof Blob) size += e[1].size;
else size += e[1].length;
}
console.log('size',size);
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));
.length
of properties keys or the size in bytes of attached data at values? – guest271314 Commented Feb 15, 2017 at 19:19Content-Length
would be if you.send
theFormData
. There are irritating things like signed URLs that nitpick everything, big time. It's funny how certain people are that you don't need the size of aFormData
. – doug65536 Commented Jul 27, 2022 at 23:48