Sending of Websocket file

Asked

Viewed 196 times

0

I need to create a chat channel for a system, this channel should allow to receive and send files(Docs, xls, png, etc...), I searched a lot on the internet and I did not find many examples, but I found one that I am trying to implement, when a user sends the file, I can’t send it back to itself or another user.

Java Serverendpoint

    @OnMessage
    public void processUpload(ByteBuffer slices, boolean last, Session session) throws IOException {

        //usado somente se for salvar o arquivo
        while(slices.hasRemaining()) {         
            fos.write(slices.get());
        }

//        try {
            if(last) {
//              session.getBasicRemote().sendBinary(buffer);
                System.out.println("Download enviado");
//              buffer = null;
            }
//      } catch (IOException e) {
//          e.printStackTrace();
//      }
    }

    @OnMessage
    public void message(Session session, String msg) {
        System.out.println("recebendo arquivo: " + msg);
        if(!msg.equals("end")) {
//          fileName = msg.substring(msg.indexOf(':')+1);
            fileName = msg.split("#")[0];
            buffer = ByteBuffer.allocate(Integer.parseInt(msg.split("#")[1])); 
            uploadedFile = new File(filePath+fileName);
            try {
                fos = new FileOutputStream(uploadedFile);
            } catch (FileNotFoundException e) {     
                e.printStackTrace();
            }
        }else {
            try {
                fos.flush();
                fos.close();                
            } catch (IOException e) {       
                e.printStackTrace();
            }
        }
    }

Front

<script>
    var ws;

    function connectChatServer() {
        ws = new WebSocket('ws://' + window.location.host + '/jboss-javaee-webapp/receive/fileserver');

        ws.binaryType = "arraybuffer";
        ws.onopen = function() {
            console.log("Connected.")
        };

        ws.onmessage = function(evt) {
            alert(evt.msg);
            jQuery('<a/>', {
                id: 'downloadFile',
                href: evt,
                style: 'display:hidden;',
                download: ''
            }).appendTo('body');

            $("#downloadFile")[0].click();
            //location.href = filepath;
        };

        ws.onclose = function() {
            alert("Connection is closed...");
        };
        ws.onerror = function(e) {
            alert(e.msg);
        }

    }

    function sendFile() {
        var file = document.getElementById('filename').files[0];
        ws.send(file.name + '#' + file.size);
        var reader = new FileReader();
        var rawData = new ArrayBuffer();            
        //alert(file.name);

        reader.loadend = function() {

        }
        reader.onload = function(e) {
            rawData = e.target.result;
            ws.send(rawData);
            console.log("arquivo sendo transferido.")
            ws.send('end');
        }

        reader.readAsArrayBuffer(file);

    }


</script>

1 answer

1

I solved the problem with the following algorithm.

Java

@OnMessage
    public void message(Session session, String msg) {
        System.out.println("recebendo arquivo: " + msg);
        if(!msg.equals("end")) {
            fileName = msg.split("#")[0];
            uploadedFile = new File(filePath+fileName);
            try {
                fos = new FileOutputStream(uploadedFile);
            } catch (FileNotFoundException e) {     
                e.printStackTrace();
            }
        }else {
            try {
                fos.flush();
                fos.close();

                FileInputStream fileInputStream = null;

                byte[] bFile = new byte[(int) uploadedFile.length()];

                try {
                    // convert file into array of bytes
                    fileInputStream = new FileInputStream(uploadedFile);
                    fileInputStream.read(bFile);
                    fileInputStream.close();

                } catch (Exception e) {
                    e.printStackTrace();
                }

                Arquivo arq = new Arquivo();
                arq.setNome(fileName);
                arq.setTipo("image/jpg");
                arq.setArquivo(bFile);
                ObjectMapper mapper = new ObjectMapper();

                session.getBasicRemote().sendText(mapper.writeValueAsString(arq));
                System.out.println("Download enviado arquivo em object");

            } catch (IOException e) {       
                e.printStackTrace();
            }
        }
    }

Javascript

    ws.onmessage = function(evt) {

                    var obj = jQuery.parseJSON(evt.data);

                    var contentType = obj.tipo;
                    var blob = b64toBlob(obj.arquivo, contentType);
                    var a = document.createElement("a");
                    document.body.appendChild(a);
                    a.style = "display: none";
                    var url = window.URL.createObjectURL(blob);
                    a.href = url;
                    a.download = obj.nome;
                    a.click();
                    window.URL.revokeObjectURL(url);

                };
function b64toBlob(b64Data, contentType, sliceSize) {
          contentType = contentType || '';
          sliceSize = sliceSize || 512;

          var byteCharacters = atob(b64Data);
          var byteArrays = [];

          for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
            var slice = byteCharacters.slice(offset, offset + sliceSize);

            var byteNumbers = new Array(slice.length);
            for (var i = 0; i < slice.length; i++) {
              byteNumbers[i] = slice.charCodeAt(i);
            }

            var byteArray = new Uint8Array(byteNumbers);

            byteArrays.push(byteArray);
          }

          var blob = new Blob(byteArrays, {type: contentType});
          return blob;
        }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.