2

Is there a possibility to send a json text with binary data?

I'am calling it multipart/form-data cause in the html form we can send text with a binary file, how to do the same with the websockets, is that possible?

so here is an example:

var arrayBuffer = new ArrayBuffer();

// lets say here we fill our array buffer with binary data in the browser

// so here we got 2 ways

// 1) First we can send the json text indicating that the next request will be a binary data file
// so using this way the next request will have ready an Id for the uploaded file if we are working
// with database

var obj = {};
obj.somedata = "hello This is a name for my item";
websocket.send(JSON.stringify(obj)); //first sending the text
websocket.send(arrayBuffer); //sending the binary data file


// 2) Second, This is the way I prefer most, but I don't know if this is possible
// we send a json object 

var obj = {};
obj.somedata = "hello This is a name for my item";
obj.file = arrayBuffer;
websocket.send(JSON.stringify(obj));

but the problem is that I can't put a binary data into a text json, the binary data gets corrupted this way, in the server side I'am using java... cause using 2 requests for sending a file and the input text data is not a good way I think, any hints?

DoublePudge
  • 95
  • 1
  • 9

1 Answers1

0

If server cannot handle binary data (which is maybe problem with configuration or your program, I'm sending binary data this way without no problem), then you can encode your data in base64 or escape them into json. But the best way would be repairing server side...

If you wanna use base64 way, look at this: https://github.com/niklasvh/base64-arraybuffer, and for example this: Base64 Encoding in Java

Community
  • 1
  • 1
Mike S.
  • 1,995
  • 13
  • 25
  • You (maybe, I don't know these things in java) can get binary data first, then parse the JSON from it and use rest as a raw data. But using base64 would be better in this case (if you are not sending lot of big binary buffers). Then you can use something as `obj.raw = encode(arrayBuffer)` and on server somethink like `Base64.decodeBase64(received.getString("raw"))` – Mike S. Sep 18 '14 at 11:52