Skip to content
Advertisement

File API – Blob to JSON

I’m trying to do some experiment with HTML5, WebSocket and File API. I’m using the Tomcat7 WebSocket implementation. I’m able to send and received text messages from the servlet. What I want to do now is to send from the servlet to the client JSON objects, but I want to avoid text message in order to skip the JSON.parse (or similar) on the client, so I’m trying to send binary messages. The servlet part is really simple:

String s = "{arr : [1,2]}";
CharBuffer cbuf = CharBuffer.wrap(s);      
CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();      
getWsOutbound().writeBinaryMessage(encoder.encode(cbuf));
getWsOutbound().flush();

After this message, on the client I see that I received a binary frame, that is converted to a Blob object (http://www.w3.org/TR/FileAPI/#dfn-Blob). The question is: is it possible to get the JSON object from the Blob? I took a look at the FileReader interface (http://www.w3.org/TR/FileAPI/#FileReader-interface), and I used code like this to inspect what the FileReader can do (the first line creates a brand new Blob, so you can test on the fly if you want):

var b = new Blob([{"test": "toast"}], {type : "application/json"});
var fr = new FileReader();
fr.onload = function(evt) {
    var res = evt.target.result;
    console.log("onload",arguments, res, typeof res);
};
fr.readAsArrayBuffer(b);

using all the “readAs…” methods that I saw on the File Reader implementation (I’m using Chrome 22). Anyway I didn’t find something useful.

Did you have any suggestion? Thanks.

Advertisement

Answer

What you’re doing is conceptually wrong. JSON is a string representation of an object, not an object itself. So, when you send a binary representation of JSON over the wire, you’re sending a binary representation of the string. There’s no way to get around parsing JSON on the client side to convert a JSON string to a JavaScript Object.

You absolutely should always send JSON as text to the client, and you should always call JSON.parse. Nothing else is going to be easy for you.

Advertisement