【发布时间】:2020-06-09 11:39:16
【问题描述】:
我将FormData(包括文件)发布到拒绝内容长度超过特定限制的请求的服务器。在执行注定会被拒绝的请求之前,我想在我的 JavaScript 客户端(浏览器)中验证内容长度。如何获取我的 (multipart/form-data) 编码的 FormData 对象的内容长度?
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 });
}
编辑:感谢您的回答,@Indgalante。仅使用字符串的length 和文件的size 不会计算正确的内容长度。
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 });
您没有考虑到表单数据在请求中进行了编码。因此,i.a.添加边界。示例中计算的内容长度为 3,但在我的 Chrome 浏览器中应为 138
和 172 在我的 Firefox 浏览器中。我不确定其他浏览器的行为。
【问题讨论】:
-
你解决了吗?我在 Safari 中遇到了一个相关问题。
-
@Soyaine 不是。我使用我的回答stackoverflow.com/a/63471719/1065654 中描述的估计
标签: javascript multipartform-data form-data content-length http-content-length