問題描述
我想從 javascript 中的 XMLHttpRequest 對象發(fā)出部分內(nèi)容請求.我正在從服務(wù)器加載一個大的二進(jìn)制文件,我寧愿從服務(wù)器流式傳輸它,類似于處理 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 來設(shè)置 Range 標(biāo)頭.Chrome 中的網(wǎng)絡(luò)檢查器顯示 Range 標(biāo)頭設(shè)置成功.但是,Accept-Encoding 標(biāo)頭設(shè)置為gzip,deflate",Chrome 不允許我設(shè)置該標(biāo)頭(來自 W3C 標(biāo)準(zhǔn)).
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).
有什么方法可以強制服務(wù)器只響應(yīng)來自 javascript 的 XMLHttpRequest 對象的 206 部分內(nèi)容?
Is there any way to force the server to respond with a 206 partial content from the XMLHttpRequest object only from javascript?
推薦答案
我想我知道為什么 206 請求不起作用了.啟用 gzip 壓縮后,如果可以對傳出數(shù)據(jù)進(jìn)行 gzip 壓縮,則范圍標(biāo)頭將被忽略.
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.
我請求的文件是一個大型二進(jìn)制文件,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 標(biāo)頭設(shè)置為 identity 也允許范圍請求正常工作的原因.但是,我無法從 XHR 更改該標(biāo)題.
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.
解決方案:更改服務(wù)器上的 mimetype 表!
Solution: Change the mimetype table on the server!
這篇關(guān)于XMLHttpRequest 206 部分內(nèi)容的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!