kingGarfield
kingGarfield

Reputation: 356

Spring HttpMediaTypeNotAcceptableException

I am trying to make an endpoint for downloading a video file. here is the code :

@GetMapping(value = "/video")
    public ResponseEntity getVideo() throws MalformedURLException {
        FileSystemResource fileSystemResource = new FileSystemResource("E:\\video\\hello.mp4");
        ResourceRegion region = new ResourceRegion(fileSystemResource,
                                                   0,
                                                   fileSystemResource.getFile().length());
        return ResponseEntity.status(HttpStatus.PARTIAL_CONTENT)
                .contentType(MediaType.valueOf("video/mp4"))
                .contentLength(fileSystemResource.getFile().length())
                .body(region);
    }

i get this respone when trying to call the url :

org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation

thank u in advance for your help

Upvotes: 0

Views: 301

Answers (1)

User9123
User9123

Reputation: 1733

1) without ResourceRegion

    @GetMapping(value = "/video")
    public ResponseEntity getVideo() throws MalformedURLException {
        FileSystemResource fileSystemResource = new FileSystemResource("E:\\video\\hello.mp4");
//        ResourceRegion region = new ResourceRegion(fileSystemResource, 0, fileSystemResource.getFile().length());
        return ResponseEntity.status(HttpStatus.PARTIAL_CONTENT)
                .contentType(MediaType.valueOf("video/mp4"))
                .contentLength(fileSystemResource.getFile().length())
                .body(fileSystemResource);
    }

2) or add converters to spring:

@Configuration
public class ApplicationConfig extends WebMvcConfigurationSupport {

    @Bean
    public ResourceRegionHttpMessageConverter regionMessageConverter() {
       return new ResourceRegionHttpMessageConverter();
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(regionMessageConverter());
        super.configureMessageConverters(converters);
    }
}

with fix controller:

@GetMapping(value = "/video")
public ResponseEntity<ResourceRegion> getVideo() {
    FileSystemResource fileSystemResource = new FileSystemResource("E:\\video\\hello.mp4");
    ResourceRegion region = new ResourceRegion(fileSystemResource, 0, fileSystemResource.getFile().length());
    return ResponseEntity.status(HttpStatus.PARTIAL_CONTENT)
            .contentType(MediaType.valueOf("video/mp4"))
            .contentLength(fileSystemResource.getFile().length())
            .body(region);
}

Upvotes: 1

Related Questions