I'm trying to upload a file via websockets with the following code:

let file=e.target.files[0]let ws=new WebSocket("ws://")ws.binaryType="arraybuffer";var reader=new FileReader();var rawData=new ArrayBuffer();ws.onopen=()=> {reader.loadend=function() {}reader.onload=function(e) {rawData=e.target.result;ws.send(rawData);console.log("Transfer complete.")}reader.readAsArrayBuffer(file);}

The websocket works with texts well, and the connection is definitly not the problem. But coming to the very detailed netty documentation, I cannot find anything how to handle the recieved BinaryWebSocketFrame. Here the java code:

public class SocketHandler extends SimpleChannelInboundHandler<Object> {@Overridepublic void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception {if (msg instanceof WebSocketFrame) {if (msg instanceof BinaryWebSocketFrame) {System.out.println("BinaryWebSocketFrame Received : ");BinaryWebSocketFrame frame=(BinaryWebSocketFrame) msg;//This is nothing more than an echo.. It is received by the client successfully.ctx.writeAndFlush(new BinaryWebSocketFrame(frame.isFinalFragment(), frame.rsv(), frame.content()));} else if (msg instanceof TextWebSocketFrame) {System.out.println("TextWebSocketFrame Received : " + ((TextWebSocketFrame) msg).text());}}}}

My problem is the BinaryWebSocketFrame.. how can I store it to a file now? Or what is contained in this bytebuf? Can I store the path where the file should be stored inside the buf?I'm not good with ByteBuffers, so please go in detail.. there is no documentation on this things happening in netty.

share|improve this question

    The BinaryWebSocketFrame.content() method returns a ByteBuf. The ByteBuf methods has a readBytes(...) method that takes an OutputStream which you could use to write to a file.

    share|improve this answer
    • can you maybe add some example code? e.g. hat are the parameters of readBytes– Felix GaeblerFeb 15 at 16:47

    I found it out... here is an code example in addition

    BinaryWebSocketFrame frame=(BinaryWebSocketFrame) msg;ByteBuf buffer=frame.content().retain();FileOutputStream outputStream=new FileOutputStream(new File("test.png"));try {if (buffer.isReadable()) {buffer.readBytes(outputStream, buffer.readableBytes());}} finally {outputStream.close();}
    share|improve this answer

      Your Answer


      By posting your answer, you agree to the privacy policy and terms of service.

      Not the answer you're looking for? Browse other questions tagged or ask your own question.