I need to create a conversation channel for a system, this channel should allow receiving and sending files (docs, xls, png, etc ...), I searched a lot on the internet and did not find many examples, but I found one that I'm trying implement, when a user submits the file, I can not send it back to itself or to 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>