XMLHttpRequest 206 Partial Content

后端 未结 2 690
Happy的楠姐
Happy的楠姐 2020-11-30 06:50

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

相关标签:
2条回答
  • 2020-11-30 07:27

    This range-request works fine for me: http://jsfiddle.net/QFdU4/

    var xhr = new XMLHttpRequest;
    
    xhr.onreadystatechange = function () {
      if (xhr.readyState != 4) {
        return;
      }
      alert(xhr.status);
    };
    
    xhr.open('GET', 'http://fiddle.jshell.net/img/logo.png', true);
    xhr.setRequestHeader('Range', 'bytes=100-200'); // the bytes (incl.) you request
    xhr.send(null);
    

    You have to make sure that the server allows range requests, though. You can test it with curl:

    $ curl -v -r 100-200 http://example.com/movie.mkv > /dev/null
    
    0 讨论(0)
  • 2020-11-30 07:41

    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.

    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.

    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.

    Solution: Change the mimetype table on the server!

    0 讨论(0)
提交回复
热议问题