🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
实现步骤如下: **1. 服务端代码** ```java @Component @ServerEndpoint(value = "/v1/download") public class DownLoadController { @OnMessage public void download(String message, Session session) throws IOException, EncodeException { File file = new File(message); FileInputStream input = new FileInputStream(file); byte[] content = new byte[1024]; while (input.read(content) != -1) { session.getBasicRemote().sendObject(content); } session.getBasicRemote().sendText(200 + ""); } } ``` **2. 前端代码** ```js var socket = null const blobList = [] /** * 连接服务端 */ function connect() { socket = new WebSocket('ws://localhost:8090/v1/download') socket.onmessage = (e) => { if (e.data instanceof Blob) { blobList.push(e.data) } if(e.data === '200') { let blob = new Blob(blobList) const link = document.createElement('a'); link.href = window.URL.createObjectURL(blob); link.download = new Date() + '.mp4' link.click(); window.URL.revokeObjectURL(link.href); } } } /** * 上传下载参数 */ function downloadFile() { socket.send('e:/upload/websocket/tem.mp4') } ``` >[warning]提醒:上面的代码下载文件时需要将文件合并,使用的计算资源是客户的浏览器,如果下载较大的文件时可能会导致客户浏览器卡。