我是TypeScript/JavaScript的新手,我正在尝试使用TypeScript和XMLHTTPRequest 2。
根据RFC 7233,多部分/byteranges响应具有以下内容:
HTTP/1.1 206 Partial Content
Date: Wed, 15 Nov 1995 06:25:24 GMT
Last-Modified: Wed, 15 Nov 1995 04:58:08 GMT
Content-Length: 1741
Content-Type: multipart/byteranges; boundary=THIS_STRING_SEPARATES
--THIS_STRING_SEPARATES
Content-Type: application/pdf
Content-Range: bytes 500-999/8000
...the first range...
--THIS_STRING_SEPARATES
Content-Type: application/pdf
Content-Range: bytes 7000-7999/8000
...the second range
--THIS_STRING_SEPARATES--
我看到了两个选项:
- 将响应的主体视为二进制数据阵列(SET
XMLHttpRequest.responseType = "arraybuffer"
),将边界字符串转换为二进制,在二进制数据阵列中搜索每个身体部位,以通过边界弦转换为二进制,提取每个有效负载的标题并将其转换为字符串?或, - 与上面的类似,但将身体视为字符串(SET
XMLHttpRequest.responseType = "text"
),标识边界串界定的身体部位,然后将有效载荷转换为二进制数据阵列?
在JavaScript/Typescript中处理/解析此类响应的正确方法是什么,因为响应包含多个身体部位,每个部件都有自己的标头(字符串)和有效载荷(二进制)?
?有更简单的方法吗?
欢迎任何建议。谢谢!
我什至不确定您如何使用"arraybuffer"
响应类型进行操作,但是我以前用过此操作来解析Multipart/byteranges响应:
function parseMultipartBody (body, boundary) {
return body.split(`--${boundary}`).reduce((parts, part) => {
if (part && part !== '--') {
const [ head, body ] = part.trim().split(/rnrn/g)
parts.push({
body: body,
headers: head.split(/rn/g).reduce((headers, header) => {
const [ key, value ] = header.split(/:s+/)
headers[key.toLowerCase()] = value
return headers
}, {})
})
}
return parts
}, [])
}
并且为了与xmlhttprequest一起使用,它可能看起来像这样:
const client = new XMLHttpRequest()
client.open('GET', 'example.pdf', true)
client.setRequestHeader('Range', 'bytes=500-999,7000-7999')
client.onreadystatechange = function() {
if (client.readyState == 4 && client.status === 206) {
const boundary = client.getResponseHeader('Content-Type').match(/boundary=(.+)$/i)[1]
if (boundary) console.log('PARTS', parseMultipartBody(client.resposeText, boundary))
}
}
client.send()
您示例响应的输出看起来像这样:
[
{
"body": "...the first range...",
"headers": {
"content-type": "application/pdf",
"content-range": "bytes 500-999/8000"
}
},
{
"body": "...the second range",
"headers": {
"content-type": "application/pdf",
"content-range": "bytes 7000-7999/8000"
}
}
]