HTML 5 video streaming + Spring boot

Viewed 766

I have this controller:

@GetMapping(value = "videos/{id}/{name}")
@ResponseBody
public final ResponseEntity<InputStreamResource>
retrieveResource(@PathVariable(value = "id") final String id,
                 @PathVariable(value = "name") final String name) throws Exception {

    File initialFile = new File(id + name);
    InputStream targetStream = new FileInputStream(initialFile);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.valueOf("video/mp4"));
    headers.set("Accept-Ranges", "bytes");
    headers.set("Expires", "0");
    headers.set("Cache-Control", "no-cache, no-store");
    headers.set("Connection", "keep-alive");
    headers.set("Content-Transfer-Encoding", "binary");

    return new ResponseEntity<>(new InputStreamResource(targetStream), headers, HttpStatus.OK);

}

when I access using the browser http://localhost:7080/videos/2/3

I see the video, but not when I put it in a HTML page:

 <div class="media-box foto">
                <video width="320" height="240" controls>

                    <video url="http://localhost:7080/videos/2/3" type="video/mp4">

                </video>
            </div>
1 Answers

Your Java code looks fine. The problem has to do with your HTML.

Please, try instead:

<div class="media-box foto">
  <video src="http://localhost:7080/videos/2/3"
         width="320" height="240" controls>
    <p>Your browser does not support HTML5 video. Here is a <a href="http://localhost:7080/videos/2/3">link to the video</a> instead.</p>
  </video>
</div>

The video format is usually not indicated unless you have several ones. For example:

<div class="media-box foto">
  <video width="320" height="240" controls>
    <source src="http://localhost:7080/videos/2/3?format=mp4" type="video/mp4">
    <source src="http://localhost:7080/videos/2/3?format=webm" type="video/webm">
    <p>Your browser does not support HTML5 video. Here is a <a href="http://localhost:7080/videos/2/3">link to the video</a> instead.</p>
  </video>
</div>

You can include other attributes like autoplay or muted. Please, see the relevant documentation on MDN.

Related