所以我设计了一个应用程序,它有一个reactjs前端,提供来自spring引导后端的内容。我有一个休息控制器,提供视频。它在大约10分钟内工作得非常好,然后我的浏览器中出现“由于网络错误导致视频播放中止”。我有什么问题吗?这应该在另一个线程或异步或其他东西上完成吗?我想这一切都是在春天完成的。
@RestController
@CrossOrigin
public class VideoDirectoryController {
@Autowired
private ConfigManager<LibraryConfig> librariesConf;
/**
*
* @param libraryName
* @param fileName
* @return
*/
@GetMapping(value = "/getVideo", produces = "video/mp4")
public byte[] getVideo(@RequestParam(value = "library") String libraryName,
@RequestParam(value = "fileName") String fileName) {
Library lib = librariesConf.getConfig().getLibraries().get(libraryName.toLowerCase());
Video video = lib.getVideoFiles().get(fileName);
lib.getRecentlyViewed().add(video);
librariesConf.getConfig().getLibraries().keySet().forEach((libr) -> System.out.println("LIBR: :" + libr));
try (FileInputStream out = new FileInputStream(lib.getFileDirectory(fileName))) {
return IOUtils.toByteArray(out);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
正如我所说,这可以正常工作大约10分钟。如果我使用:3000(前端),如果我直接点击获取视频的URL(:8080 / getVideo),它都会这样做
任何帮助表示赞赏我以前从未在Spring Boot中使用多媒体。
我建议使用StreamingResponseBody
或直接写入OutputStream
的HttpServletRequest
。连同设置响应的内容类型和大小。
@GetMapping(value = "/getVideo", produces = "video/mp4")
public void getVideo(@RequestParam(value = "library") String libraryName,
@RequestParam(value = "fileName") String fileName, HttpServletResponse response) {
Library lib = librariesConf.getConfig().getLibraries().get(libraryName.toLowerCase());
Video video = lib.getVideoFiles().get(fileName);
lib.getRecentlyViewed().add(video);
librariesConf.getConfig().getLibraries().keySet().forEach((libr) -> System.out.println("LIBR: :" + libr));
try (FileInputStream out = new FileInputStream(lib.getFileDirectory(fileName))) {
return StreamUtils.copy(out, response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
或者使用StreamingResponseBody
相同
@GetMapping(value = "/getVideo", produces = "video/mp4")
public StreamingResponseBody getVideo(@RequestParam(value = "library") String libraryName,
@RequestParam(value = "fileName") String fileName) {
Library lib = librariesConf.getConfig().getLibraries().get(libraryName.toLowerCase());
Video video = lib.getVideoFiles().get(fileName);
lib.getRecentlyViewed().add(video);
librariesConf.getConfig().getLibraries().keySet().forEach((libr) -> System.out.println("LIBR: :" + libr));
return new StreamingResponseBody() {
public void write(OutputStream out2) throws IOException {
try (FileInputStream out = new FileInputStream(lib.getFileDirectory(fileName))) {
StreamUtils.copy(out, out2);
}
}
};
}