webscoket进度下载

如果你不相信努力和时光,那么成果就会是第一个选择辜负你的。不要去否定你自己的过去,也不要用你的过去牵扯你现在的努力和对未来的展望。不是因为拥有希望你才去努力,而是去努力了,你才有可能看到希望的光芒。webscoket进度下载,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

@Autowired
private WebSocketServer webSocketHandler;
@Autowired
AsyncDownloadService asyncDown;
@GetMapping("/download/txt/{filename}")
@ResponseBody
public Object downloadTxtFile(@PathVariable("filename") String filename, String sessionId,HttpServletResponse response) throws IOException, InterruptedException {
    Path filePath = Paths.get("D:\\CentOS-7-x86_64-DVD-1810.zip");
   
    // 创建一个文件系统资源对象
    FileSystemResource file = new FileSystemResource(filePath.toFile());
    // 设置响应头
    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"");
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

    
    //第一种方式异步方式
    //asyncDown.downloadFileWithProgress(1+"", filePath);
    
    //ServletOutputStream outputStream = response.getOutputStream();
    try (FileInputStream fis = new FileInputStream(filePath.toFile())) {
        byte[] buffer = new byte[1024];
        long totalSize = Files.size(filePath);
        long totalBytesRead = 0;
        int readBytes = 0;
        while ((readBytes = fis.read(buffer)) != -1) {
        	//outputStream.write(buffer, 0, readBytes);
            // 假设有个地方可以记录或报告进度,实际应用中可能需要存储到数据库或者内存队列
            totalBytesRead += readBytes;
            double progress = (double) totalBytesRead / totalSize * 100;
        	System.out.println(progress);
        	Thread.sleep(1000);
            webSocketHandler.sendDownloadProgress(sessionId, progress);
        }
    } catch (IOException e) {
        response.reset(); // 尝试重置响应以防止已提交
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred during file download.");
    }
    // 构建并返回ResponseEntity
    return ResponseEntity.ok()
            .headers(headers)
            .contentLength(file.contentLength())
            .body(file);
}


webScoket配置
@Component
@Service
@ServerEndpoint("/api/websocket/{sid}")
public class WebSocketServer {

    private static final Map<String, Session> sessions = new ConcurrentHashMap<>();

    @Autowired
    private FileDownloadService downloadService; // 假设这是你的文件下载服务

    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) {
        sessions.put(sid, session);
    }

    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
        sessions.values().removeIf(s -> s.getId().equals(session.getId()));
    }

    @OnError
    public void onError(Throwable error) {
    }

    @OnMessage
    public void onMessage(String message) {
        // 可以处理消息,但在这个场景下我们主要关注推送进度
    }

    public void sendDownloadProgress(String sid, double progressPercentage) throws IOException {
        Session session = sessions.get(sid);
        if (session != null && session.isOpen()) {
            String progressUpdate = "Download Progress: " + progressPercentage + "%";
            session.getBasicRemote().sendText(progressUpdate);
        }
    }
}


异步方式
@Service
public class AsyncDownloadService {
@Autowired
private WebSocketServer webSocketHandler;
@Async
//synchronized
public void downloadFileWithProgress(String sessionId, Path filePath) {
	try (FileInputStream fis = new FileInputStream(filePath.toFile())) {
      byte[] buffer = new byte[1024];
      long totalSize = Files.size(filePath);
      long totalBytesRead = 0;
      int readBytes = 0;
      while ((readBytes = fis.read(buffer)) != -1) {
          // 假设有个地方可以记录或报告进度,实际应用中可能需要存储到数据库或者内存队列
          totalBytesRead += readBytes;
          double progress = (double) totalBytesRead / totalSize * 100;
          System.out.println(progress);
          webSocketHandler.sendDownloadProgress(sessionId, progress);
      }
  } catch (IOException e) {
           
  }
}


<script type="text/javascript">
$(function () {
  //判断浏览器是否支持WebSocket
  var supportsWebSockets = 'WebSocket' in window || 'MozWebSocket' in window;
  if (supportsWebSockets) {
    //建立WebSocket连接(ip地址换成自己主机ip)
    var  ws = new WebSocket("ws://localhost:8080/api/websocket/1");

    ws.onopen = function(){
        //当WebSocket创建成功时,触发onopen事件
        console.log("websocket连接成功");
        //ws.send("hello"); //将消息发送到服务端
    }
    ws.onmessage = function(e){
        //当客户端收到服务端发来的消息时,触发onmessage事件,参数e.data包含server传递过来的数据
        console.log("收到数据");
        console.log(e.data);
    }
    ws.onclose = function(e){
        //当客户端收到服务端发送的关闭连接请求时,触发onclose事件
        console.log("websocket已断开");
    }
    ws.onerror = function(e){
        //如果出现连接、处理、接收、发送数据失败的时候触发onerror事件
        console.log("websocket发生错误"+e);
    } 
  }else{
    layer.alert("您的浏览器不支持 WebSocket!");
  }
});
</script>

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/200892.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!