栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot静态视频实时播放的实现代码

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot静态视频实时播放的实现代码

问题描述

Spring Boot API 定义 GET 请求 API , 返回视频流。前端通过

解决方法

Spring framework 文件请求处理

import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

import javax.servlet.http.HttpServletRequest;
import java.nio.file.Path;

@Component
public class NonStaticResourceHttpRequestHandler extends ResourceHttpRequestHandler {

  public final static String ATTR_FILE = "NON-STATIC-FILE";

  @Override
  protected Resource getResource(HttpServletRequest request) {
    final Path filePath = (Path) request.getAttribute(ATTR_FILE);
    return new FileSystemResource(filePath);
  }

}

Controller 层

@RestController
@AllArgsConstructor
public class FileRestController {

  private final NonStaticResourceHttpRequestHandler nonStaticResourceHttpRequestHandler;

  
  @GetMapping("/video")
  public void videoPreview(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String path = request.getParameter("path");
    Path filePath = Paths.get(path);
    if (Files.exists(filePath)) {
      String mimeType = Files.probeContentType(filePath);
      if (!StringUtils.isEmpty(mimeType)) {
 response.setContentType(mimeType);
      }
      request.setAttribute(NonStaticResourceHttpRequestHandler.ATTR_FILE, filePath);
      nonStaticResourceHttpRequestHandler.handleRequest(request, response);
    } else {
      response.setStatus(HttpServletResponse.SC_NOT_FOUND);
      response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
    }
  }

}

相关资料

How do I return a video with Spring MVC so that it can be navigated using the html5 tag?

https://stackoverflow.com/questions/3303029/http-range-header

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/135592.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号