java – Upload a video using html <video> tag with Spring-ThrowExceptions

Exception or error:

I am trying to develop an application. I get video chunks as byte array from queue and send them to browser without saving as a file. However my code isnot working.Can anyone provide some advice on how to achieve this please. Thank you in advance.

@GetMapping("/stream")
public void lasting(HttpServletRequest request,HttpServletResponse response) throws IOException {
        OutputStream output=response.getOutputStream();
        response.setContentType("video/mp4");
        String range = request.getHeader("Range");
        File file=new File("temp.mp4");

        byte[] arr= Files.readAllBytes(Paths.get(file.getAbsolutePath()));
        int size=arr.length;
        if(range!=null) {
            String[] parts=range.replace("bytes=", "").split("-");
            long start=Long.parseLong(parts[0].trim());
            long end;
            if(parts.length>1) {
                end=Long.parseLong(parts[1].trim());
            }
            else {
                end=size-1;

            }
            long chunksize=end-start+1;
            output.write(( "Content-type: video/mp4\r\n" +
                    "Accept-Ranges: bytes \r\n"+
                    "Content-Range: bytes "+start +"-"+end+"/"+arr.length+"\r\n"+
                    "Content-Length: " +
                    chunksize+
                    "\r\n\r\n").getBytes());
            output.flush();
            long a=end;
            long b=start;

            byte[] d=Arrays.copyOfRange(arr, (int)start,(int) end+1);


            output.write(d);


            output.write("\r\n\r\n".getBytes());
            output.flush();



        }
        else {
            output.write(( "Content-type: video/mp4\r\n" +
                    "Content-Length: " +arr.length+
                    "\r\n\r\n").getBytes());


            output.write(arr);
            output.write("\r\n\r\n".getBytes());
            output.flush();

        }
    }

Also my html code is here

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Consumer's stream</title>
</head>
<body>
    <video id="/video" src="http://locallhost:9999/stream" type="video/mp4"></video>
</body>
</html>
How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *