I post FormData (including files) to a server that rejects requests with a content-length that exceeds a specific limit. I'd like to validate the content-length in my JavaScript client (browser) before doing a request that is doomed to be rejected. How do I get the content-length of my (multipart/form-data) encoded FormData object?
const formData = new FormData();
formData.append('text', text);
formData.append('file', file);
if (getContentLength(formData) > limit) {
alert('Content length limit is exceeded');
} else {
fetch(url, { method: 'POST', body: formData });
}
Edit: Thanks for your answer, @Indgalante. Just using length of a string and size of a file does not calculate the correct content length.
function getContentLength(formData) {
const formDataEntries = [...formData.entries()]
const contentLength = formDataEntries.reduce((acc, [key, value]) => {
if (typeof value === 'string') return acc + value.length
if (typeof value === 'object') return acc + value.size
return acc
}, 0)
return contentLength
}
const formData = new FormData();
formData.append('text', 'foo');
alert(`calculated content-length is ${getContentLength(formData)}`);
fetch('https://httpbin.org/post', { method: 'POST', body: formData });
You did not consider that the form data is encoded in the request. Thereby, i.a. boundary is added. The calculated content-length in the example is 3, but should be 138 in my Chrome browser
and 172 in my Firefox browser. I'm unsure how other browsers behave.


One approach could be FormData.entries() so you can iterate over all your data and get a final content length. We will also need a
spread operatorover an array or you could useArray.from()to convert the iterator returned by.entries()into a proper array.Code example below, I didn't test it with files but let me know if you have any edge case with this one.