不接受Spring MVC ResponseEntity< Resource>一个ImputStreamResource? [英] Doesn't accept Spring MVC ResponseEntity<Resource> an ImputStreamResource?

查看:1223
本文介绍了不接受Spring MVC ResponseEntity< Resource>一个ImputStreamResource?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 ResponseEntity< Resource> 作为控制器方法响应类型,使用Spring MVC发送jpg图像。

I'm trying to send a jpg image with Spring MVC using ResponseEntity<Resource> as the controller method response type.

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

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.

是否有任何其他方法可以为 ResponseEntity <使用 InputStream 作为资源 / code>?

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

提示:对于大内容10MB +,设置ContentLength很重要。如果你错过了一些浏览器将无法正确下载它。 (没有ContentLength的确切文件大小是浏览器所依赖的)

这篇关于不接受Spring MVC ResponseEntity&lt; Resource&gt;一个ImputStreamResource?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆