流式传输视频文件 mp4,使用 Spring Boot 2 控制器 StreamingResponseBody。

huangapple go评论72阅读模式
英文:

stream video file mp4 with Spring Boot 2 Controller StreamingResponseBody

问题

@Controller
public class StreamController {

    @RequestMapping(path = { "/stream-video-file" }, method = RequestMethod.GET)
    public ResponseEntity<StreamingResponseBody> streamFile(
            HttpServletRequest request,
            HttpServletResponse response) {

        File file = new File("/path/to/file.mp4");
        if (!file.isFile()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }

        StreamingResponseBody stream = out -> {
            try {
                final InputStream inputStream = new FileInputStream(file);

                byte[] bytes = new byte[1024];
                int length;
                while ((length = inputStream.read(bytes)) >= 0) {
                    out.write(bytes, 0, length);
                }
                inputStream.close();
                out.flush();

            } catch (final Exception e) {
                LOG.error("Exception while reading and streaming data {}", e);
            }
        };

        final HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "video/mp4");
        headers.add("Content-Length", Long.toString(file.length()));

        return ResponseEntity.ok().headers(headers).body(stream);
    }
}

EDIT ----

I find another way to do the job, without using StreamingResponseBody, but using the response header "Range-Content".

A very good explanation here: https://stackoverflow.com/questions/3303029/http-range-header#answer-18745164

and here: https://github.com/saravanastar/video-streaming


<details>
<summary>英文:</summary>

I&#39;m trying to stream a video file mp4 with Spring Boot 2 , I followed some tutorial and the solution should be simple... like the controller I copied below...  but don&#39;t work for me.

I cant understand why.. 
When I put the url in my browser, the default video player appear, loading... 
after a timeout i receive a &quot;net::ERR_CONTENT_LENGTH_MISMATCH 200 &quot; in the browser console..

If I omit the headers.add(&quot;Content-Length&quot;, Long.toString(file.length()));  the loading is very fast but nothing happen... 


@Controller
public class StreamController {

@RequestMapping(path = { &quot;/stream-video-file&quot; }, method = RequestMethod.GET)
public ResponseEntity&lt;StreamingResponseBody&gt; streamFile(
		HttpServletRequest request,
		HttpServletResponse response) {

	File file = new File(&quot;/path/to/file.mp4&quot;);
	if (!file.isFile()) {
		return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);

	}

	StreamingResponseBody stream = out -&gt; {

		try {
			final InputStream inputStream = new FileInputStream(file);

			byte[] bytes = new byte[1024];
			int length;
			while ((length = inputStream.read(bytes)) &gt;= 0) {
				out.write(bytes, 0, length);
			}
			inputStream.close();
			out.flush();

		} catch (final Exception e) {
			LOG.error(&quot;Exception while reading and streaming data {} &quot;, e);
		}

	};

	final HttpHeaders headers = new HttpHeaders();
	headers.add(&quot;Content-Type&quot;, &quot;video/mp4&quot;);
	headers.add(&quot;Content-Length&quot;, Long.toString(file.length()));

	return ResponseEntity.ok().headers(headers).body(stream);
}

}



What I&#39;m missing?...


EDIT ----

I find another way to do the job, without using StreamingResponseBody, but using the response header &quot;Range-Content&quot; .  

A very good explanation here: https://stackoverflow.com/questions/3303029/http-range-header#answer-18745164  

and here:  https://github.com/saravanastar/video-streaming

</details>


# 答案1
**得分**: 1

```java
// 添加注释到这一行:
headers.add("Content-Type", "video/mp4");
英文:

Comment this line:

headers.add(&quot;Content-Type&quot;, &quot;video/mp4&quot;);

huangapple
  • 本文由 发表于 2020年10月14日 02:00:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/64340673.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定