Implementation code of spring boot static video real time play

Time:2020-11-20

Problem description

The spring boot API defines the get request API and returns the video stream. The front end loads and plays the video through the < video > tag. The effect is that the entire video resource must be loaded into the browser before it can be played. Moreover, the default progress bar of < video > tag cannot control the video playback. The final desired effect is that the video stream is loaded while playing, and the control of the player works normally.

resolvent

Spring framework file request processing


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 layer

@RestController
@AllArgsConstructor
public class FileRestController {

  private final NonStaticResourceHttpRequestHandler nonStaticResourceHttpRequestHandler;

  /**
   *Preview video file, support byte range request
   */
  @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());
    }
  }

}

Related information

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

The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.