Java实现视频预览

342 阅读1分钟

直接上代码

	/**
     * 获取视频流
     * @author 欧阳锋feng
     * @Date 2022-10-09
     */
    @ApiOperation(value = "获取视频")
    @GetMapping("/getVideo/{fileId}/{fileSuffix}")
    public void getVideo(HttpServletResponse response, @PathVariable("fileId") String fileId, @PathVariable("fileSuffix") String fileSuffix) {
        if (!"mp4".equals(fileSuffix)) {
            throw new ServiceException("在线查看视频暂且支持MP4格式!!!");
        }
        response.reset();
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        response.addHeader("Access-Control-Allow-Headers", "Content-Type");
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            inputStream = minioTemplate.view((fileId + "." + fileSuffix));
            response.setHeader(HttpHeaders.CONTENT_TYPE, "video/mp4");
            int d;
            byte[] b = new byte[1024];
            while ((d = inputStream.read(b)) != -1) {
                outputStream.write(b, 0, d);
            }
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("视频播放失败");
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.flush();
                    outputStream.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }