3 回答

TA貢獻1951條經驗 獲得超3個贊
下面是一個異步版本,它首先將表單數據轉換為 Blob。從中可以檢索要發送到服務器的實際大小。
因此,您不會發布表單數據,而是發送生成的 blob。
async function test() {
// Create some dummy data
const fd = new FormData()
fd.set('a', 'b')
// acquire an actual raw bytes as blob of what the request would send
const res = new Response(fd)
const blob = await res.blob()
blob.text && (
console.log('what the actual body looks like'),
console.log(await blob.text())
)
// can't use own blob's type since spec lowercase the blob.type
// so we get the actual content type
const type = res.headers.get('content-type')
// the acutal content-length size that's going to be used
console.log('content-length before sending', blob.size)
// verify
const testRes = await fetch('https://httpbin.org/post', {
method: 'POST',
body: blob, // now send the blob instead of formdata
headers: { // use the real type (and not the default lowercased blob type)
'content-type': type
}
})
const json = await testRes.json()
const headers = new Headers(json.headers)
console.log('form that got posted:', JSON.stringify(json.form))
console.log('content-length that was sent', headers.get('content-length'))
}
但是,這在IE和野生動物園中不起作用
IE沒有抓取(但無論如何它已經死了)
野生動物園有這個錯誤。
all doe,將表單數據替換為多填充版本(如 https://github.com/jimmywarting/FormData)可能有助于您將表單數據直接(同步)轉換為 blob,而無需使用提取 API(使用 )。也就是說,如果您需要更廣泛的瀏覽器支持formData._blob()

TA貢獻1818條經驗 獲得超3個贊
我仍然不知道是否有可能計算出確切的大小,但您至少可以嘗試估計它:
/**
* Estimate the content length of (multipart/form-data) encoded form data
* object (sent in HTTP POST requests).
* We do not know if you can get the actual content length.
* Hence, it is estimated by this function.
* As soon as {@link https://stackoverflow.com/q/62281752/1065654 this}
* question is answered (correctly), the correct calculation should be used.
*
* @param formData
*/
function estimateContentLength(formData: FormData) {
// Seems to be 44 in WebKit browsers (e.g. Chrome, Safari, etc.),
// but varies at least in Firefox.
const baseLength = 50; // estimated max value
// Seems to be 87 in WebKit browsers (e.g. Chrome, Safari, etc.),
// but varies at least in Firefox.
const separatorLength = 115; // estimated max value
let length = baseLength;
const entries = formData.entries();
for (const [key, value] of entries) {
length += key.length + separatorLength;
if (typeof value === 'object') {
length += value.size;
} else {
length += String(value).length;
}
}
return length;
}

TA貢獻1862條經驗 獲得超6個贊
一種方法可能是 FormData.entries(),因此您可以循環訪問所有數據并獲取最終的內容長度。我們還需要一個 over 數組,或者您可以使用 將 返回的迭代器轉換為正確的數組。spread operatorArray.from().entries()
下面的代碼示例,我沒有用文件測試它,但讓我知道你是否有任何邊緣情況與這個。
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
}
添加回答
舉報