有没有办法从 JavaScript 异步请求 Web 资源的特定部分(例如前 100 个字节)?
我认为这可以通过 XmlHttpRequest
设置其 Range
header 来完成。但是,如果服务器应用内容编码(大多数情况下都是默认的),则字节范围将应用于编码数据,而不是原始数据。每HTTP/1.1 :
When an entity-body is included with a message, the data type of that body is determined via the header fields Content-Type and Content- Encoding. These define a two-layer, ordered encoding model:
entity-body := Content-Encoding( Content-Type( data ) )
Byte range specifications in HTTP apply to the sequence of bytes in the entity-body […].
这使得检索到的内容变得无用,因为如果不检索(并连接)编码资源的其余部分就无法对其进行解码。
显然不可能从客户端禁用内容编码,因为 XMLHttpRequest
prohibits Accept-Encoding
被更改。
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () { /* ... */ };
xhr.open("GET", url, true);
xhr.setRequestHeader("Range", "bytes=0-99");
xhr.setRequestHeader("Accept-Encoding", "identity"); // not allowed
xhr.send();
是否有其他方法可以实现此目的(假设无法在服务器上禁用内容编码)?
最佳答案
您可以尝试使用模拟ajax行为的旧式技术,例如使用您提到的所有 header 加载隐藏的iframe(并且可能允许编码 header )并从此类隐藏的iframe获取数据。以下是使用隐藏 iframe 上传多部分数据的示例:example 。您可以根据需要更改它。也许会有帮助。
关于javascript - 异步请求 Web 资源的特定部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26692525/