如何在Spring Boot控制器中返回映像并像文件系统一样提供服务

2022-09-02 23:27:56

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

我有一个Android客户端(其代码我无法更改),目前正在获得如下图像:

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

位置 是映像的位置(CDN 上的静态资源)。现在,我的 Spring Boot API 终结点需要以相同的方式像文件资源一样运行,以便相同的代码可以从 API 获取映像(Spring Boot 版本 1.3.3)。url

所以我有这个:

@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

正在从处理程序 [public 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 代码发送的内容类型标头)

编辑

注释后的代码(设置内容类型,取出):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中,它不会出错,但图像不会显示。


答案 1

我相信这应该有效:

@RequestMapping(value = "/Image/{id:.+}", method = RequestMethod.GET)
public ResponseEntity<byte[]> getImage(@PathVariable("id") String id) {
    byte[] image = imageService.getImage(id);
    return ResponseEntity.ok().contentType(MediaType.IMAGE_JPEG).body(image);
}

请注意,内容类型设置为 ,而不是直接设置为 。ResponseEntityHttpServletResponse


答案 2

终于修复了这个问题...我不得不向我的子类添加一个:ByteArrayHttpMessageConverterWebMvcConfigurerAdapter

@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);
}

推荐