My Javascript code that is run in client-side needs to read a binary file that is stored in the server. How can I do it for all browsers?
I have found solutions with ActiveXObject - FileSystemObject that are only working in Internet Explorer.
Thanks
My Javascript code that is run in client-side needs to read a binary file that is stored in the server. How can I do it for all browsers?
I have found solutions with ActiveXObject - FileSystemObject that are only working in Internet Explorer.
Thanks
function getXHR(){
var xhr;
try{
xhr = new XMLHttpRequest();
}catch(e){
try{
xhr = new ActiveXObject("MSXML2.XMLHTTP.6.0");
}catch(e2){
try{
xhr = new ActiveXObject("MSXML2.XMLHTTP");
}catch(e3){}
}
}
return xhr;
}
function getBinaryData(url, callback){
var xhr = getXHR();
xhr.open("GET", url, !!callback);
if(callback){
xhr.onload = function(){callback(xhr, true)};
xhr.onerror = function(){callback(xhr, false)};
}
xhr.send();
return callback ? undefined : xhr.responseText;
}
You would then use getBinaryData to get the file. with asynchronous, it will call the callback with arguments the xhr object itself (you would read the responseText property), and whether it was successful. Synchronously, it returns the binary data.
new XMLHttpRequest(), which is the W3C standardfor classic asp server side javascript (from an old document server i have)
as it is server side all browser will download the file, in this case this piece of code was not to give direct access to file and was used after user login check.
Server.ScriptTimeout=500;//this might take some time
var docs_type="application/pdf";
var filename="...";//put your filename here (relative path)
var objStream = Server.CreateObject("ADODB.Stream");
try {
objStream.Open();
objStream.Type=1;//binary
objStream.LoadFromFile(Server.MapPath(filename));
Response.AddHeader("Content-Length", objStream.Size);
Response.ContentType=docs_type;//the type of document you are serving
Response.AddHeader("Content-Disposition", "attachment; filename=your_filename.pdf");
while(!objStream.EOS&&Response.IsClientConnected) {
Response.BinaryWrite(objStream.Read(4*1024*256));
Response.Flush();
}
objStream.Close();
Response.End();
} catch(e) {
Response.Write("Error serving document<br>");
Response.End();
}
}