zoukankan      html  css  js  c++  java
  • SpringBoot静态视频实时播放

    img

    问题描述

    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;
    
        /**
         * 预览视频文件, 支持 byte-range 请求
         */
        @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());
            }
        }
    
    }
    

    相关资料

    本文由博客一文多发平台 OpenWrite 发布!

  • 相关阅读:
    Swift -- Swfit 笔记
    web -- CSS 图片宽高不固定的垂直居中方法
    web -- Angularjs 笔记2
    web -- Angularjs 笔记
    web -- Angularjs 备忘录应用
    Swift -- swift 函数代码
    Swift -- 创建空数组和空字典
    Linux -- FresBSD的镜像文件说明
    Linux -- ubuntu下安装程序的三种方法
    Linux -- Ubuntu 命令2
  • 原文地址:https://www.cnblogs.com/springforall/p/12143041.html
Copyright © 2011-2022 走看看