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>