Monday, October 8, 2007

GET single byte from big binary file using JavaScript and XMLHttpRequest

Full example and testing page

For FireFox, trick is to map bytes to user part of unicode.
(Idea by mgran)
xmlhttp.open("GET", fileName, false);
xmlhttp.setRequestHeader("Range", "bytes="+position+"-"+position);
if (navigator.userAgent.indexOf("MSIE") == -1)
{
    eval("xmlhttp.overrideMimeType('text/plain; charset=x-user-defined')");
}
xmlhttp.send(null)
return xmlhttp.responseText.charCodeAt(0) & 0xFF; 
For Explorer in VBScript, because it is possible to access responseBody in VB but is not possible to overrideMimeType in IE.
(Idea by mgran's reader)
Function readbyteIE(fileName, position)
Dim xhr
Set xhr = CreateObject("Microsoft.XMLHTTP")

xhr.Open "GET", fileName, False
xhr.setRequestHeader "Range", "bytes=" & position & "-" & position
xhr.send Null

readbyteIE=AscB(MidB(xhr.responseBody, 1, 1)) 
End Function
Credits to mgran and his readers

PS: I'm new in browser scripting. Please correct me if I missed something.

2 comments:

Anonymous said...

Thanks, I didn't know it was possible to mix vbscript with javascript this way.

Did you try this with Opera or Safari?

Z said...

I don't have to Safari or Opera, please try it and let me know. Thx