有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Spring MVC视频类型转发并以字节形式发送[]

我正在尝试用SpringMVC和Angular2创建一个视频平台。但我不能让这个视频向前或向后。我也没有让rest控制器将视频发送到字节块,只发送整个视频

@RequestMapping(value = "/method2/{name}", method = RequestMethod.GET)
public void getDownload(HttpServletResponse response, HttpServletRequest request,@PathVariable String name)
        throws IOException, ServletException {

    String filePath;
    if (name.contains("webm")) {
        filePath = webm;
        System.out.println("WEBM");
    } else if (name.contains("mp4")) {
        filePath = mp4;
        System.out.println("MP4");
    } else {
        filePath = mkv;
        System.out.println("MKV");
    }
    // Get your file stream from wherever.
    ServletContext context = request.getServletContext();

    File downloadFile = new File(filePath);
    FileInputStream inputStream = new FileInputStream(downloadFile);

    // Set the content type and attachment header.
    String headerKey = "Content-Disposition";
    String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
    response.setHeader(headerKey, headerValue);
    String mimeType = context.getMimeType(filePath);
    if (mimeType == null) {
        // set to binary type if MIME mapping not found
        mimeType = "application/octet-stream";
    }
    response.setContentType(mimeType);

    // Copy the stream to the response's output stream.
    IOUtils.copy(inputStream, response.getOutputStream());
    response.flushBuffer();
}

ant我的html

<video  width='360' height='240' [vgMedia]="media" #media id="singleVideo" preload="auto" crossorigin>
    <source src="********/movies/method2/mp4" type="video/mp4">
</video>

我在这里看过很多帖子,但没有一篇能帮我做到这一点

EDIT1。方法3

@RequestMapping(method = RequestMethod.GET, value = "/method3/{name}")
public StreamingResponseBody stream(@PathVariable String name) throws FileNotFoundException {
    String filePath;
    if (name.contains("webm")) {
        filePath = webm;
        System.out.println("WEBM");
    } else if (name.contains("mp4")) {
        filePath = mp4;
        System.out.println("MP4");
    } else {
        filePath = mkv;
        System.out.println("MKV");
    }
    File videoFile = new File(filePath);
    final InputStream videoFileStream = new FileInputStream(videoFile);
    return (os) -> {
        readAndWrite(videoFileStream, os);
    };
}
private void readAndWrite(final InputStream is, OutputStream os) throws IOException {
    byte[] data = new byte[2048];
    int read = 0;
    while ((read = is.read(data)) > 0) {
        os.write(data, 0, read);
    }
    os.flush();
}

谢谢


共 (1) 个答案

  1. # 1 楼答案

    看看这个post,这是我以前写的,关于如何使用春季提供的StreamingResponseBody播放流媒体视频