I'm using Play Framework 2.0, Javascript and WebSockets. As in the example I have an AKKA actor that has knowledge of all the websockets. The single WebSockets.In have a ListenerCallback object that handle incoming requests from the client side. On the Client side I have Javascript/jquery to send formular data serialized in JSON to the websocket. This works pretty well for simple inputs. But now I want to do the same with a file. So I must convert the file data somehow to JSON data (e.g. base64). Does anybody know how to do this properly? I want to "collect" the file within Javascript and then send it via JSON to the websocket. I know base64 is not very efficient, if somebody has an alternative, please tell me.
Thanks
It is possible, however you have to use the WebSocket
and FileReader
API, which are only supported on newer browsers. Javascript has now a TypedArray
datatype, which can be used to transfer bytes. For example, given the following HTML:
<form>
<input type="file" id="picture" />
</form>
You need to observe the change
event on the file input field. On the Javascript side (jQuery):
$("#picture").change(function(){
var reader = new FileReader;
reader.onloadend = function (bytes) {
var ws = new WebSocket("ws://host/path");
ws.send(bytes);
}
reader.readAsArrayBuffer(this.files[0]);
});
WebSocket PDU are minimally framed (only two bytes header), and when you send()
, the browser should take care of setting the proper opcode for binary transfer, and on the server you should be able to read the stream of raw bytes. I am looking at the Play API now to supply a minimal working example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With