不接受 Spring MVC ResponseEntity<Resource> 输入流资源?

问题描述 投票:0回答:2

我正在尝试使用 Spring MVC 发送 jpg 图像,使用

ResponseEntity<Resource>
作为控制器方法响应类型。

如果资源是

FileSystemResource
它工作正常,但是当我尝试使用
InputStreamResource
时,
ResourceHttpMessageConverter
询问内容长度,并且
InputStreamResource
抛出异常(来自
AbstractResource
方法,因为没有任何文件阅读长度)。如果该方法返回
ResourceHttpMessageConverter
null
将继续。

还有其他方法可以将

InputStream
用作
Resource
ResponseEntity
吗?

image spring spring-mvc response inputstream
2个回答
2
投票

例如,您可以将其复制到字节数组(或直接使用输入流——我还没有使用输入流对其进行测试)。

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

提示:对于 10MB 以上的大内容,设置 ContentLength 非常重要。如果您错过了某些浏览器将无法正确下载它。 (在没有 ContentLength 的情况下,其工作的确切文件大小取决于浏览器)


0
投票

试试这个:

return ResponseEntity.ok()
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=filename.jpg")
            .contentLength(length)
            .contentType(MediaType.APPLICATION_OCTET_STREAM_VALUE)
            .body(new InputStreamResource(inputStream));
© www.soinside.com 2019 - 2024. All rights reserved.