Reputation: 1140
I'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'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 "net::ERR_CONTENT_LENGTH_MISMATCH 200 " in the browser console..
If I omit the headers.add("Content-Length", Long.toString(file.length())); the loading is very fast but nothing happen...
@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);
}
}
What I'm missing?...
EDIT ----
I find another way to do the job, without using StreamingResponseBody, but using the response header "Range-Content" .
A very good explanation here: HTTP Range header
and here: https://github.com/saravanastar/video-streaming
Upvotes: 2
Views: 5283