XMLHttpRequest 206 部分内容

2022-01-15 00:00:00 xmlhttprequest javascript ajax

我想从 javascript 中的 XMLHttpRequest 对象发出部分内容请求.我正在从服务器加载一个大的二进制文件,我宁愿从服务器流式传输它,类似于处理 html5 视频的方式.

I would like to issue a partial content request from an XMLHttpRequest object in javascript. I'm loading a large binary file from the server, and I'd rather stream it from the server similar to how html5 video is handled.

我可以使用 setRequestHeader 来设置 Range 标头.Chrome 中的网络检查器显示 Range 标头设置成功.但是,Accept-Encoding 标头设置为gzip,deflate",Chrome 不允许我设置该标头(来自 W3C 标准).

I can use setRequestHeader to set the Range header. The Network inspector in Chrome shows that the Range header is set successfully. However, the Accept-Encoding header is set to "gzip,deflate", and Chrome will not let me set that header (from W3C standards).

有什么方法可以强制服务器只响应来自 javascript 的 XMLHttpRequest 对象的 206 部分内容?

Is there any way to force the server to respond with a 206 partial content from the XMLHttpRequest object only from javascript?

推荐答案

我想我知道为什么 206 请求不起作用了.启用 gzip 压缩后,如果可以对传出数据进行 gzip 压缩,则范围标头将被忽略.

I think I figured out why the 206 request wasn't working. With gzip compression enabled, the range header gets ignored if the outgoing data can be gzipped.

我请求的文件是一个大型二进制文件,nginx 将其解释为具有 mimetype application/octet-stream.这是被 gzip 压缩的 mimetype 之一.如果我将文件重命名为 .png 文件类型,则图像/png mimetype 不会被压缩,因此范围请求可以正常工作.

The file I was requesting was a large binary file, which nginx interpreted as having mimetype application/octet-stream. This is one of the mimetypes that gets gzipped. If I renamed the file to have a .png filetype, the image/png mimetype is not gzipped, and hence the range request works correctly.

这也是为什么将带有 curl 的 Accept-Encoding 标头设置为 identity 也允许范围请求正常工作的原因.但是,我无法从 XHR 更改该标题.

This is also why setting the Accept-Encoding header with curl to identity also allows the range request to work fine. However, I cannot change that header from an XHR.

解决方案:更改服务器上的 mimetype 表!

Solution: Change the mimetype table on the server!

相关文章