zoukankan      html  css  js  c++  java
  • boot实现视频播放

    SpringBoot+vue的项目中,实现前端播放视频

    SpringBoot 定义GET请求ApI,返回视频流,前端通过

    话不多说,走起


    一、新建如下类,用于返回视频流

    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
    @RequestMapping("/file")
    @AllArgsConstructor
    public class FileRestController {

    private final NonStaticResourceHttpRequestHandler nonStaticResourceHttpRequestHandler;


    @GetMapping("/video")
    public void videoPreview(HttpServletRequest request, HttpServletResponse response) throws Exception {

    //假如我把视频1.mp4放在了static下的video文件夹里面
    //sourcePath 是获取resources文件夹的绝对地址
    //realPath 即是视频所在的磁盘地址
    String sourcePath = ClassUtils.getDefaultClassLoader().getResource("").getPath().substring(1);
    String realPath = sourcePath +"static/video/1.mp4";


    Path filePath = Paths.get(realPath );
    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());
    }
    }

    }


    三、后端url测试

    到了这一步基本可以通过访问后端url进行视频播放了
    测试:http://localhost:8080/file/video

    不出意外的话是可以播放的,如果播放不了的,再检查下视频所在的物理地址

    第三步没问题的话进行第四步


    四、前端播放

    前端播放代码

    <video controls autoplay src="http://localhost:8080/file/video"/>

    这里有个要注意的点:建议 src属性 直接放在<video>里,别放在<video>标签下的<source>里,会播放不了的
    over
    ————————————————
    版权声明:本文为CSDN博主「sJLei_38759449」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/weixin_38759449/article/details/104496464

  • 相关阅读:
    java多态课后作业
    java继承与接口课后作业
    java数组课后作业
    javaString课后作业
    Java类与对象课后作业
    java方法课后作业
    java基本知识课后作业
    读《大道至简》第二章有感
    课堂作业(字符串转化并计算)
    读《大道至简》第一章有感
  • 原文地址:https://www.cnblogs.com/niudaxianren/p/14980378.html
Copyright © 2011-2022 走看看