最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JS How to measure size of FormData object? - Stack Overflow

programmeradmin1浏览0评论

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
  • What do you mean by "size"? The .length of properties keys or the size in bytes of attached data at values? – guest271314 Commented Feb 15, 2017 at 19:19
  • in bytes. and FormData doesn't have length – Nikolai Commented Feb 15, 2017 at 19:20
  • What's meant by the size, is what the Content-Length would be if you .send the FormData. 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 a FormData. – doug65536 Commented Jul 27, 2022 at 23:48
Add a comment  | 

3 Answers 3

Reset to default 17

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);

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));
发布评论

评论列表(0)

  1. 暂无评论