Doesn't accept Spring MVC ResponseEntity<Resource> an ImputStreamResource?

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-03 04:03:17

问题


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

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.

Is there any other way to manage to use an InputStream as Resource for the ResponseEntity?


回答1:


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

Hint: for big content 10MB+ it is important to set the ContentLength. If you miss that some Browsers will not download it correctly. (The exact file size up to which it works without ContentLength is browser dependend)




回答2:


Try this:

return ResponseEntity.ok()
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=filename.jpg")
            .contentLength(length)
            .contentType(MediaType.APPLICATION_OCTET_STREAM_VALUE)
            .body(new InputStreamResource(inputStream));


来源:https://stackoverflow.com/questions/8049153/doesnt-accept-spring-mvc-responseentityresource-an-imputstreamresource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!