我遇到了通过弹簧控制器下载网格fs存储图像的问题。当试图打开下载的文件时,图像查看器说它已损坏,结果表明图像是base64格式。
有控制器部分:
@Override
@RequestMapping(value = "/image_download", method = RequestMethod.GET)
public ResponseEntity<byte[]> downloadImage(...) throws IOException {
final GridFSDBFile image = getImageFromGrifFs(...);
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.valueOf(image.getContentType()));
headers.setContentDispositionFormData("attachment", image.getFileName());
final byte[] content = IOUtils.toByteArray(image.getInputStream());
return new ResponseEntity<>(content, headers, HttpStatus.OK);
}
Spring版本是4.3.11。 以下是消息转换器:
@Override
public void configureMessageConverters(final List<HttpMessageConverter<?>> converters) {
converters.add(new MappingJackson2HttpMessageConverter());
converters.add(byteArrayHttpMessageConverter());
super.configureMessageConverters(converters);
}
@Bean
public ByteArrayHttpMessageConverter byteArrayHttpMessageConverter() {
final ByteArrayHttpMessageConverter arrayHttpMessageConverter = new ByteArrayHttpMessageConverter();
arrayHttpMessageConverter.setSupportedMediaTypes(getSupportedMediaTypes());
return arrayHttpMessageConverter;
}
private List<MediaType> getSupportedMediaTypes() {
final List<MediaType> list = new ArrayList<>();
list.add(MediaType.IMAGE_JPEG);
list.add(MediaType.IMAGE_PNG);
list.add(MediaType.IMAGE_GIF);
list.add(MediaType.APPLICATION_OCTET_STREAM);
return list;
}
我还尝试在控制器中使用InputStreamResource:
return ResponseEntity.ok()
.contentLength(image.getLength())
.contentType(MediaType.parseMediaType(image.getContentType()))
.body(new InputStreamResource(image.getInputStream()));
但得到例外:
无法写内容:找不到类com.mongodb.gridfs.GridFSDBFile $ MyInputStream
的序列化程序
任何帮助表示赞赏。谢谢。
答案 0 :(得分:0)
在我做了更多挖掘后,我找到了很好的解释:https://stackoverflow.com/a/44943494/2421204
确实向RequestMapping添加(生成=&#34; image / jpeg&#34;)解决了这个问题。
@RequestMapping(value = "/image_download", method = RequestMethod.GET, produces = "image/jpeg")
下载的图像是二进制文件。