1

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

let file = e.target.files[0]
let ws = new WebSocket("ws://127.0.0.1:8080/")
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> {

    @Override
    public 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.

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

can you maybe add some example code? e.g. hat are the parameters of readBytes
2

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();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.