springboot+websocket怎么传递文件
时间: 2025-01-30 16:24:39 浏览: 37
### Spring Boot WebSocket 实现文件上传与下载
#### 文件上传实现方式
为了在Spring Boot环境中利用WebSocket实现文件上传,可以采用如下策略:
- **客户端准备**:创建一个HTML表单用于选择要上传的文件,并通过JavaScript读取该文件的内容并将其转换为Base64编码字符串。之后,使用WebSocket API将此数据发送给服务器。
```html
<input type="file" id="fileInput"/>
<button onclick="sendFile()">Send File</button>
<script>
function sendFile() {
var file = document.getElementById('fileInput').files[0];
if (file) {
let reader = new FileReader();
reader.onloadend = function () {
const socket = new WebSocket('ws://localhost:8080/fileUpload');
socket.onopen = () => {
socket.send(reader.result);
};
}
reader.readAsDataURL(file); // 将文件转码为base64格式
} else {
console.log("No file selected");
}
}
</script>
```
- **服务端接收**:定义`TextWebSocketHandler`子类来处理来自客户端的消息,在接收到消息后解码Base64字符串恢复原始二进制流,并保存到指定位置[^1]。
```java
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
public class FileUploadHandler extends TextWebSocketHandler {
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
String payload = message.getPayload(); // 获取Base64编码后的文件内容
byte[] decodedBytes = Base64.getMimeDecoder().decode(payload.split(",")[1]); // 解析出实际的数据部分
try (OutputStream outputStream = new FileOutputStream(new File("/path/to/save/" + UUID.randomUUID()))) {
outputStream.write(decodedBytes);
}
System.out.println("Received and saved the uploaded file.");
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
super.afterConnectionClosed(session, status);
}
}
```
#### 文件下载实现方式
对于文件下载操作,则是从服务器向客户端推送文件资源。这里可以通过先加载目标文件至内存中再经由WebSocket通道传递出去的方式达成目的;不过需要注意的是这种方式适合较小规模的文件传输场景,因为整个过程都是同步阻塞式的,如果涉及较大体积的文件可能会占用较多系统资源甚至造成性能瓶颈。
- **服务端配置**
编写专门负责响应特定事件触发时向外分发所需文档的服务端逻辑,比如监听某个命令词或动作标识符作为启动条件之一。
```java
// 假设有一个名为downloadRequest的方法用来接受客户端发起的下载请求
@OnMessage
public void downloadRequest(String requestPath){
Path filePath = Paths.get(requestPath);
if (!Files.exists(filePath)) {
throw new RuntimeException("The requested resource does not exist!");
}
try(InputStream inputStream = Files.newInputStream(filePath)){
byte[] bytes = IOUtils.toByteArray(inputStream);
// 发送前同样需要把字节数组转化为Base64编码形式以便于网络传输
String encodedString = "data:" + Files.probeContentType(filePath)+";base64,"+ Base64.getEncoder().encodeToString(bytes);
webSocketSession.sendMessage(new TextMessage(encodedString));
} catch(IOException e){
logger.error(e.getMessage(), e);
}
}
```
- **客户端获取**
当从服务器那里得到回应后,解析返回的信息头得知MIME类型以及具体内容,最后调用浏览器内置API完成本地存储流程。
```javascript
const ws = new WebSocket('ws://localhost:8080/download');
ws.onmessage = async function(event){
const link = document.createElement('a');
link.href = event.data; // data URL containing base64-encoded content with MIME-type prefix
link.download = 'filename.ext'; // Set desired filename here
document.body.appendChild(link);
await link.click();
URL.revokeObjectURL(link.href);
document.body.removeChild(link);
};
```
阅读全文
相关推荐



















