WebSocket Upload Files from Javascript

Upload files to a websocket server is very easy, just send file as binary data. Example of HTML client:

 

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Upload Files</title>

</head>

<body>

    <h2>File Upload</h2>

    Select file

    <input type="file" id="filename" />

    <br>

    <input type="button" value="Connect" onclick="connectChatServer()" />

    <br>

    <input type="button" value="Upload" onclick="sendFile()" />

    <script>

        var ws;

        function connectChatServer() {

            ws = new WebSocket("ws://127.0.0.1");

            ws.binaryType = "arraybuffer";

            ws.onopen = function() {

                alert("Connected.")

            };

            ws.onmessage = function(evt) {

                alert(evt.msg);

            };

            ws.onclose = function() {

                alert("Connection is closed...");

            };

            ws.onerror = function(e) {

                alert(e.msg);

            }

        }

        function sendFile() {

            var file = document.getElementById('filename').files[0];

            var reader = new FileReader();

            var rawData = new ArrayBuffer();            

            reader.loadend = function() {

            }

            reader.onload = function(e) {

                rawData = e.target.result;

                ws.send(rawData);

                alert("the File has been transferred.")

            }

            reader.readAsArrayBuffer(file);

        }

    </script>

</body>

</html>

Once binary message is received by server, just create a TFileStream and copy binary data. Example of Server:

procedure OnWSServerBinary(Connection: TsgcWSConnection; const Data: TMemoryStream);

var

  oFile: TFileStream;

begin

  oFile := TFileStream.Create('file.dat', fmCreate);

  Try

    oFile.CopyFrom(Data, Data.Size);

  Finally

    oFile.Free;

  End;

end;


 You can download a compiled application which shows how you can upload a file in your server.

 WebSocket Upload File Demo

 

 Read more about our sgcWebSockets components

 sgcWebSockets Components