gpt4 book ai didi

java - 使用 java websocket API 和 Javascript 上传文件

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:00:00 26 4
gpt4 key购买 nike

我正在研究websocket,用websocket/json做过聊天程序。但我坚持文件上传 ATM。任何建议和答案将不胜感激。

服务器端:

package websocket;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

import javax.websocket.CloseReason;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/receive/fileserver")
public class FileServer {
@OnOpen
public void open(Session session, EndpointConfig conf) {
System.out.println("chat ws server open");
}

@OnMessage
public void processUpload(ByteBuffer msg, boolean last, Session session) {
System.out.println("Binary message");

FileOutputStream fos = null;
File file = new File("D:/download/tmp.txt");
try {
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}

byte readdata = (byte) -999;
while(readdata!=-1) {
readdata=msg.get();
try {
fos.write(readdata);
} catch (IOException e) {
e.printStackTrace();
}
}

}

@OnMessage
public void message(Session session, String msg) {
System.out.println("got msg: " + msg + msg.length());

}

@OnClose
public void close(Session session, CloseReason reason) {
System.out.println("socket closed: "+ reason.getReasonPhrase());
}

@OnError
public void error(Session session, Throwable t) {
t.printStackTrace();

}
}

客户:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Chat</title>
<script type="text/javascript" src="/MyHomePage/jquery-2.0.3.min.js"></script>
</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://localhost:8080/MyHomePage/receive/fileserver");

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.readAsBinaryString(file);

}


</script>
</body>
</html>

服务器端关闭原因消息如下

套接字关闭:解码的文本消息对于输出缓冲区来说太大,端点不支持部分消息

Q1:好像是根据关闭原因找的是文本处理方式,而不是二进制处理方式,请问如何解决?

问题 2:我应该将数据类型更改为 Blob 以在 javascript 端传输文件吗?那怎么办呢?

额外的问题:任何人都可以链接 websocket 文件传输的示例源(java websocket 或 javascript 之一/两者)?

感谢阅读:)

最佳答案

经过一些研究和尝试,我发现“reader.readAsBinaryString(file);”是问题 1 的原因。将其更改为“reader.readAsArrayBuffer(file);”我的第一个问题已经解决了。

此外,由于 websocket 会自动将一个文件传输为多个部分数据,因此我将源代码更改如下。 这行得通! 仅当文件大小不是那么大时。 :/

更改服务器端源:

package websocket;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

import javax.websocket.CloseReason;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/receive/fileserver")
public class FileServer {
static File uploadedFile = null;
static String fileName = null;
static FileOutputStream fos = null;
final static String filePath="d:/download/";

@OnOpen
public void open(Session session, EndpointConfig conf) {
System.out.println("chat ws server open");
}

@OnMessage
public void processUpload(ByteBuffer msg, boolean last, Session session) {
System.out.println("Binary Data");

while(msg.hasRemaining()) {
try {
fos.write(msg.get());
} catch (IOException e) {
e.printStackTrace();
}
}

}

@OnMessage
public void message(Session session, String msg) {
System.out.println("got msg: " + msg);
if(!msg.equals("end")) {
fileName=msg.substring(msg.indexOf(':')+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();
}
}
}

@OnClose
public void close(Session session, CloseReason reason) {
System.out.println("socket closed: "+ reason.getReasonPhrase());
}

@OnError
public void error(Session session, Throwable t) {
t.printStackTrace();

}
}

浏览器(客户端)端:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Chat</title>
<script type="text/javascript" src="/MyHomePage/jquery-2.0.3.min.js"></script>
</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://localhost:8080/MyHomePage/receive/fileserver");

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];
ws.send('filename:'+file.name);
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);
alert("the File has been transferred.")
ws.send('end');
}

reader.readAsArrayBuffer(file);

}


</script>
</body>
</html>

我仍然不知道如何传输更大的文件。 (我怀疑自动超时和/或缓冲区大小)。有什么建议吗?

关于java - 使用 java websocket API 和 Javascript 上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21769470/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com