I was looking to implement the front end functionality to download set of videos using java script. There are bunch of processes that run on the downloaded videos. Currently I am using XmlHttpRequest that can only start processing the bytes after downloading the entire video. Below is the sample code. I have taken any http request for problem statement. Processing starts in "xmlhttp.readyState==4" block.
function loadXMLDoc() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://www.thomas-bayer.com/sqlrest/CUSTOMER/1",true);
xmlhttp.send();
}
I was trying to find out if there is any way to download the response in chunks and start processing it while it is getting downloaded. This is something similar to what we can do using java.io.Inputstream package. Please see a code below which reads byte by byte with a chunk size as 1 byte.
try {
URL url = new URL("http://www.thomas-bayer.com/sqlrest/CUSTOMER/1");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
InputStream is = conn.getInputStream();
byte buff[] = new byte[1];
int readData = 0;
StringBuilder response = new StringBuilder();
while (true) {
readData = is.read(buff);
if (readData == -1)
break;
response.append(new String(buff, 0, readData));
}
is.close();
conn.disconnect();
System.out.println(response);
} catch (MalformedURLException e) {
// handle exception
} catch (IOException e) {
// handle exception
}
Please suggest. Thanks for your help in advance.
Related
I wonder if there is any simple way to get request processing percent with ajax.(not jQuery)
I tried some way to get this percent on my own.
in my php file I Set response content-length.
and then I use this code for progress percent:
function ajaxPost(url,data,callBack,progress)
{
var postPar = data;
//for(var f in data) postPar += f+'='+data[f]+'&';
var xmlhttp;
if (window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
else
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange=function()
{
var percent = 0;
if(xmlhttp.readyState>=3) percent = Math.ceil(xmlhttp.responseText.length*100/xmlhttp.getResponseHeader('Content-length'));
progress(percent);
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
callBack(xmlhttp.responseText);
}
}
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(postPar);
}
but there is some problems:
1- I cant use this function for another site except this.(because other sites may not have content-length header)
2- this code is not working with upload requests.
Now I want to know is there any way to improve this or maybe some better way to do ?
thanks in advance...
I have the following code :
<head>
<script>
function startChanging() {
var elems = document.getElementsByTagName("img");
for(var i=0; i < elems.length; i++)
{
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp["elem"] = elems[i];
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
this["elem"].src = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "http://myurl.com/somescript.php", true);
xmlhttp.send();
}
};
</script>
</head>
<body onload="startChanging()">
<img src="https://www.google.com/images/srpr/logo11w.png">
<br/>
<img src="https://www.google.com/images/srpr/logo11w.png">
<br/>
<img src="https://www.google.com/images/srpr/logo11w.png">
</body>
Even though I create a new instance of XMLHttpRequest for each iteration and add the current element to an attribute, when the request returns a response only the last img element is changed.
I am looking for a simple solution to change the src of the img element without iterating through all the elements again when the response comes. I would like a pure Javascript solution (read: no JQuery).
I am certainly doing something wrong here I just don't understand what. Any help would be appreciated.
In your for loop, you are overwriting the xmlhttp variable so when you get into the onreadystatechage function and you check the value of xmlhttp.readyState, it will not be checking the right object.
I'd suggest this fix which changes two things:
It puts each ajax call into it's own IIFE which keeps the xmlhttp variable separate for each ajax call.
It passes elems[i] into the closure so you don't have to do the property saving hack.
Code:
function startChanging() {
var elems = document.getElementsByTagName("img");
for(var i=0; i < elems.length; i++)
{
(function(obj) {
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
obj.src = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "http://myurl.com/somescript.php", true);
xmlhttp.send();
})(elems[i]);
}
};
One possible approach:
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
this.elem.src = this.responseText;
}
}
As you see, I've replaced all the references to xmlhttp within that handler function to this.
The problem is even though you've created a new AJAX-serving object at each step of the loop, each newly-created 'readystatechange' handler function referred to the same object known under xmlhttp variable.
In general, this is quite a common problem when someone works with a variable declared within a loop yet referred by functions created in the same loop. Stumble upon this once or twice, and you'll begin to see the pattern. )
xmlhttp.send();
Put data into the send method:
xmlhttp.send(data);
Source: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
void send();
void send(ArrayBuffer data);
void send(ArrayBufferView data);
void send(Blob data);
void send(Document data);
void send(DOMString? data);
void send(FormData data);
Where data is a JavaScript variable, you can put anything into. If you want multipart message, you'd use var data = new FormData(); and put data into it using data.append('image', file); for file upload via ajax for example.
If no multipart, simply put anything in like:
data = { images: document.getElementsByTagName("img") }
I have web application that can download from dropbox.com. The application is written using Javascript. I'm using the dropbox.min.js http://code.google.com/p/dropbox-js/ library running on a client.
This is a function of the library:
client.readFile(name, function(error, data) {
if (error) {
return showError(error); // Something went wrong.
}
saveFile(name, data);
});
saveFile(name, data) is my function doing the following:
var saveFile = function(file, data)
{
var xmlhttp = getXmlHttp();
xmlhttp.open('POST', 'saving.php', true);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("fileName=" + file + "&data=" + data);
}
function getXmlHttp(){
var xmlhttp;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
The problem is: while I'm trying to download assets (e.g. jpg doc, gif, etc.), I only receive 1kb instead of the full file. Are there any workarounds?
The official JavaScript library can download binary files in browsers that support XHR level 2 (Chrome, Firefox, IE 10).
See the sample code in the getting started document, and use the blob: true option when calling readFile.
I want to display the binary code of a music file. But somehow the code below doesn't seem to work. Any suggestions??
function binary() {
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","1.wav",true);
xmlhttp.overrideMimeType("text/plain; charset=x-user-defined");
xmlhttp.onreadystatechange = function(buffer) {
var binaryCode = "";
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var binStr = this.responseText;
for (var i=0; i<binStr.length; i++) {
var byte = binStr.charCodeAt(i) & 0xff; // get byte at i
binaryCode += byte;
}
}
document.getElementById("result").innerHTML = binaryCode; // should display binary code
};
xmlhttp.send();
}
Not all byte values are expressible in a string and will not appear or cause the string to cut off short.
XMLHttpResponse.ResponseText/ResponseXML will return the http response content as a string. Any byte values of 0 for example will terminate the string.
Have the server return a Base64 representation of the bytes and decode into byte values on the client side.
Your code seems to be working fine on my chrome browser.
What is exactly the problem your are experimenting ?
You may want to display the binary in an hexadecimal form by doing something like:
binaryCode += '0x' + byte.toString(16) + ' '
edit:
this jsfiddle works on my chrome:
http://jsfiddle.net/e6Kfk/
However, i do not think that this method is crossbrowser, especially if you want to deal with ie (haven't tested it though)
I would like to retrieve fullpath of a file and pass it to javascript. The requirement is that I need to retrieve XML file using JavaScript.
If it is a file you can access relatively to your web page do something like:
var xmlDoc=new ActiveXObject("MSXML.DOMDocument");
xmlDoc.async="false";
xmlDoc.load("abc.xml");
Assuming you have your web page next to the abc.xml...
This doesn't specify how to get full path to the XML - do youi still need it or loading it is enough?
For cross browser (from: http://developer.apple.com/internet/webcontent/xmlhttpreq.html)
var req;
loadXMLDoc("abc.xml");
function loadXMLDoc(url) {
req = false;
// branch for native XMLHttpRequest object
if(window.XMLHttpRequest && !(window.ActiveXObject)) {
try {
req = new XMLHttpRequest();
} catch(e) {
req = false;
}
// branch for IE/Windows ActiveX version
} else if(window.ActiveXObject) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
req = false;
}
}
}
if(req) {
req.onreadystatechange = processReqChange;
req.open("GET", url, true);
req.send("");
}
}
function processReqChange() {
// only if req shows "loaded"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
// ...processing statements go here...
alert(req.responseXML);
} else {
alert("There was a problem retrieving the XML data:\n" + req.statusText);
}
}
}
If you know the exact file up front, you can create a server-side program (i.e. service) to read the file, parse it and output it.
Then you'll just need to write some Javascript to make an AJAX call to this service (check out a Javascript library like Prototype or JQuery) to read the output of the service and thus the contents of the file.