如何从spring控制器返回视频?

vsnjm48y  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(908)

我有一个简单的spring引导控制器,它返回一个视频字节作为资源

@Override
    public ResponseEntity<Resource> getVideoFileAsVideo(final Long videoId) {
        final Resource videoResource = videoService.getVideoFile(videoId);
        final VideoDto video = videoService.getVideoById(videoId);

        return ResponseEntity.ok()
            .contentType(MediaType.parseMediaType("video/" + video.getFileExtension()))
            .header(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment; filename=video_%s.%s", videoId, video.getFileExtension()))
            .body(videoResource);
    }

我犯了这个错误。如何修复?

org.springframework.http.converter.HttpMessageNotWritableException: No converter for [class java.util.ImmutableCollections$List12] with preset Content-Type 'video/mp4'
    at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:313) ~[spring-webmvc-5.2.2.RELEASE.jar!/:5.2.2.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:226) ~[spring-webmvc-5.2.2.RELEASE.jar!/:5.2.2.RELEASE]
    at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:82) ~[spring-web-5.2.2.RELEASE.jar!/:5.2.2.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:124) ~[spring-webmvc-5.2.2.RELEASE.jar!/:5.2.2.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver.doResolveHandlerMethodException(ExceptionHandlerExceptionResolver.java:403) ~[spring-webmvc-5.2.2.RELEASE.jar!/:5.2.2.RELEASE]
    at org.springframework.web.servlet.handler.AbstractHandlerMethodExceptionResolver.doResolveException(AbstractHandlerMethodExceptionResolver.java:61) ~[spring-webmvc-5.2.2.RELEASE.jar!/:5.2.2.RELEASE]
    at org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver.resolveException(AbstractHandlerExceptionResolver.java:141) ~[spring-webmvc-5.2.2.RELEASE.jar!/:5.2.2.RELEASE]
    at org.springframework.web.servlet.handler.HandlerExceptionResolverComposite.resolveException(HandlerExceptionResolverComposite.java:80) ~[spring-webmvc-5.2.2.RELEASE.jar!/:5.2.2.RELEASE]
    ```
ohtdti5x

ohtdti5x1#

检查资源对象导入包。当我使用这个代码视频字节数组返回。是否尝试返回字节数组而不是资源?

InputStream is = getClass().getClassLoader().getResourceAsStream("sample.mp4");
        byte[] videoResource = IOUtils.toByteArray(is);

        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType("video/mp4"))
                .header(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment; filename=video_%s.%s", 1, "mp4"))
                .body(videoResource);

相关问题