I'm trying to send a jpg image with Spring MVC using ResponseEntity<Resource>
as the controller method response type.
If the resource is a FileSystemResource
it works fine but when I try to use an InputStreamResource
the ResourceHttpMessageConverter
ask for the content lenght and InputStreamResource
throws an exception (from AbstractResource
method because there is not any file to read lenght from). ResourceHttpMessageConverter
would continue if the method returned null
instead.
Is there any other way to manage to use an InputStream
as Resource
for the ResponseEntity
?
You can copy it to an byte array for example (or use the Input stream directly -- I have not tested it with an input stream).
@RequestMapping(value = "/{bid}/image", method = RequestMethod.GET)
public HttpEntity<byte[]> content(@PathVariable("bid") final MyImage image) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(...);
headers.setContentLength(image.getSize());
return new HttpEntity<byte[]>(this.image.getContentAsByteArray(), headers);
}
Hint: for big content 10MB+ it is important to set the ContentLength. If you miss that some Browsers will not download it correctly. (The exact file size up to which it works without ContentLength is browser dependend)
Try this:
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=filename.jpg")
.contentLength(length)
.contentType(MediaType.APPLICATION_OCTET_STREAM_VALUE)
.body(new InputStreamResource(inputStream));