小编典典

如何在Spring Boot控制器中返回映像并用作文件系统

spring-boot

我尝试了Stackoverflow中给出的各种方法,也许我错过了一些东西。

我有一个Android客户端(我的代码无法更改),该客户端当前正在显示如下图像:

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();

url图像的位置在哪里(CDN上的静态资源)。现在,我的Spring Boot
API端点需要以相同的方式像文件资源一样工作,以便相同的代码可以从API获取图像(Spring Boot版本1.3.3)。

所以我有这个:

@ResponseBody
@RequestMapping(value = "/Image/{id:.+}", method = RequestMethod.GET, consumes = MediaType.ALL_VALUE, produces = MediaType.IMAGE_JPEG_VALUE)
public ResponseEntity<byte[]> getImage(@PathVariable("id")String id) {
    byte[] image = imageService.getImage(id);  //this just gets the data from a database
    return ResponseEntity.ok(image);
}

现在,当Android代码尝试获取时,http://someurl/image1.jpg我在日志中收到此错误:

解决处理程序中的异常[公共org.springframework.http.ResponseEntity
com.myproject.MyController.getImage(java.lang.String)]:org.springframework.web.HttpMediaTypeNotAcceptableException:找不到可接受的表示形式

当我插入http://someurl/image1.jpg浏览器时,也会发生相同的错误。

奇怪的是我的测试签出确定:

Response response = given()
            .pathParam("id", "image1.jpg")
            .when()
            .get("MyController/Image/{id}");

assertEquals(HttpStatus.OK.value(), response.getStatusCode());
byte[] array = response.asByteArray(); //byte array is identical to test image

如何使它表现得像以正常方式投放的图像?(请注意,我无法更改android代码正在发送的content-type标头)

编辑

注释后的代码(设置内容类型,取出produces):

@RequestMapping(value = "/Image/{id:.+}", method = RequestMethod.GET, consumes = MediaType.ALL_VALUE)
public ResponseEntity<byte[]> getImage(@PathVariable("id")String id, HttpServletResponse response) {
    byte[] image = imageService.getImage(id);  //this just gets the data from a database
    response.setContentType(MediaType.IMAGE_JPEG_VALUE);
    return ResponseEntity.ok(image);
}

在浏览器中,这似乎给了一个字符串化的垃圾(我猜是字节)。在Android中,它不会出错,但是图像不会显示。


阅读 253

收藏
2020-05-30

共1个答案

小编典典

最后,解决了这个问题......我有一个添加ByteArrayHttpMessageConverter到我的WebMvcConfigurerAdapter子类:

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    final ByteArrayHttpMessageConverter arrayHttpMessageConverter = new ByteArrayHttpMessageConverter();
    final List<MediaType> list = new ArrayList<>();
    list.add(MediaType.IMAGE_JPEG);
    list.add(MediaType.APPLICATION_OCTET_STREAM);
    arrayHttpMessageConverter.setSupportedMediaTypes(list);
    converters.add(arrayHttpMessageConverter);

    super.configureMessageConverters(converters);
}
2020-05-30